Junior — Middle
Why can't any data type be used as a dictionary key in Python?
sobes.tech AI
Answer from AI
In Python, a dictionary key can only be a hashable (immutable) object. This is because the dictionary is implemented as a hash table, and its hash is used for quick key lookup.
If the object is mutable (for example, a list or a dictionary), its hash may change over time, which would break the integrity of the data structure and lead to errors.
Therefore, keys must be:
- Immutable (for example, strings, numbers, tuples of immutable elements).
- Implementing the
__hash__and__eq__methods to compare and index correctly.
Example:
# Correct
my_dict = {('a', 1): 'value'}
# Error
my_dict = {[1, 2]: 'value'} # TypeError: unhashable type: 'list'