Why must dictionary keys (and set elements) be hashable, and what makes an object hashable in Python?
Short answer
Dictionaries and sets use HASHING internally for O(1) average lookup, requiring keys to have a stable, consistent hash value (via __hash__) that doesn't change during the object's lifetime — this is why mutable types like list and dict CAN'T be dictionary keys (their contents…
Advertisement
AModel answer
Dictionaries and sets use HASHING internally for O(1) average lookup, requiring keys to have a stable, consistent hash value (via __hash__) that doesn't change during the object's lifetime — this is why mutable types like list and dict CAN'T be dictionary keys (their contents, and thus their hash, could change), while immutable types like str, int, and tuple (of hashable elements) can.
valid_dict = {("a", 1): "value"} # OK: tuple of hashable elements is hashable
# invalid_dict = {["a", 1]: "value"} # TypeError: unhashable type: 'list'Real-world example
Understanding why you must convert a list to a tuple before using it as a dictionary key or adding it to a set.
Likely follow-ups
- How would you make a CUSTOM class's instances usable as dictionary keys, by implementing __hash__ and __eq__?
Related topics