Sobes.tech
Junior — Middle

Why is using mutable objects as keys in a Python dictionary not allowed?

sobes.tech AI

Answer from AI

In Python, dictionary keys must be hashable and immutable objects. Mutable objects, such as lists or dictionaries, cannot be used as keys because:

  • Hash must remain constant: When a key is added to a dictionary, its hash is computed. If the object changes, the hash will change, and the dictionary will not be able to find that key.
  • Violation of dictionary integrity: Changing a key after adding it will lead to errors when searching or deleting elements.

For example, attempting to use a list as a key will cause an error:

my_dict = {}
key = [1, 2, 3]
my_dict[key] = 'value'  # TypeError: unhashable type: 'list'

Therefore, immutable types such as strings, numbers, and tuples (if they contain only immutable elements) are used as keys.

Why is using mutable objects as keys in a Python… - sobes.tech