Sobes.tech
Junior — Middle

Explain why objects that can be hashed are necessary for keys in a dictionary.

sobes.tech AI

Answer from AI

In Python, a dictionary (dict) is implemented as a hash table, where keys are used for fast data access. To be used as a key in a dictionary, an object must be hashable, meaning it has an immutable state and implements the __hash__ method.

This is necessary to:

  • Calculate the hash value of the key for quick lookup.
  • Ensure that the key does not change after being placed in the dictionary, otherwise data access will be incorrect.

For example, strings and tuples are hashable, while lists are not because they are mutable.

my_dict = {}
my_dict['key'] = 'value'  # string is hashable

# my_dict[[1, 2, 3]] = 'value'  # raises error, list is not hashable

Thus, using hashable objects guarantees correct and efficient dictionary operation.