Sub topic 4
Why some objects can be keys and others cannot
This chapter assumes you know Python basics, the difference between mutable and immutable objects, and how to use lists, tuples, dicts, and sets. It explains the rule behind dict keys and set elements and the errors you see when you break it.
The rule
Dict keys and set elements must be hashable. An object is hashable if it has a hash value that never changes during its lifetime, and it can be compared to other objects with ==. Python gets the hash value by calling hash(obj).
In practice, immutable built-in types such as int, str, float, bool, bytes, and frozenset are hashable. Mutable containers such as list, dict, and set are not.
print(hash(42))
print(hash("hello"))
print(hash((1, 2)))
try:
hash([1, 2])
except TypeError as e:
print(e) # unhashable type: 'list'The exact numbers from hash differ between runs for strings, so do not rely on them. Only the behavior matters: hashable objects return an integer, and unhashable ones raise TypeError.
Why hashing is needed
A dict and a set are built on a hash table. The hash table stores each key in a slot chosen from its hash value. To look up a key, Python computes the hash, jumps to the matching slot, and then confirms the match with ==. This is why lookups stay fast even when the collection is large.
This design only works if the hash of a stored key never changes. Suppose a list could be a key. You store it under the hash of [1, 2], then append 3. The list now hashes differently, so Python would look in the wrong slot and fail to find it. Python avoids this by refusing mutable containers as keys.
The diagram below shows the lookup steps.
The contract between hash and equality
Hashable objects must follow one rule: if a == b, then hash(a) == hash(b). Python relies on this to find equal keys in the same slot.
This is why numbers of different types behave as one key when they are equal.
d = {1: "int"}
d[1.0] = "float"
d[True] = "bool"
print(d) # {1: 'bool'}Here 1, 1.0, and True are equal and have the same hash. The dict keeps the first key object (1) and overwrites the value.
The reverse is not required. Two objects with the same hash may be unequal, which is called a collision. Python handles collisions by comparing with ==.
Tuples: hashable only if their contents are
A tuple is immutable, but it is hashable only if every item inside it is hashable. The hash of a tuple is built from the hashes of its items.
locations = {(1, 2): "tuple of ints works"}
print(locations[(1, 2)])
try:
bad = {(1, [2, 3]): "oops"}
except TypeError as e:
print(e) # unhashable type: 'list'The second tuple is still a tuple, but it holds a list, so hashing it fails. Python reports the inner offender, 'list', not 'tuple'. Read the error text carefully when you debug this.
Hashability of your own classes
Instances of classes you write are hashable by default. Their hash comes from the object's identity, and two instances are equal only if they are the same object.
If you define __eq__ without __hash__, Python sets __hash__ to None, which makes instances unhashable. This protects you from breaking the rule above.
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __eq__(self, other):
return (self.x, self.y) == (other.x, other.y)
try:
{Point(1, 2): "a"}
except TypeError as e:
print(e) # unhashable type: 'Point'To make such a class usable as a key, define __hash__ from the same fields that __eq__ compares, and do not change those fields afterward.
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __eq__(self, other):
return (self.x, self.y) == (other.x, other.y)
def __hash__(self):
return hash((self.x, self.y))
seen = {Point(1, 2): "a"}
print(seen[Point(1, 2)]) # aSummary of common types
| Type | Hashable? | Reason |
|---|---|---|
| `int`, `float`, `str`, `bytes`, `bool` | Yes | Immutable |
| `tuple` | Only if all items are hashable | Hash is built from items |
| `frozenset` | Yes, if its items are hashable | Immutable set |
| `list`, `dict`, `set` | No | Mutable |
| Custom class, default | Yes | Hash from identity |
| Custom class with `__eq__` only | No | `__hash__` set to `None` |
Practical consequences
- To use a list as a key, convert it first:
tuple(my_list)works if its items are hashable. - To store a set inside a set or as a dict key, use
frozenset. - Hashability is checked when you insert or look up, so the error appears at that line, not when you build the object.
Exercise
Why does {[1, 2]: "a"} raise a TypeError while {(1, 2): "a"} works, and what happens with {(1, [2]): "a"}?
Show answer
A dict key must be hashable, which requires a hash value that stays fixed. A list is mutable, so it is unhashable and raises TypeError: unhashable type: 'list'. A tuple of ints is immutable and its hash comes from its items, so it works. The tuple (1, [2]) contains a list, so hashing it fails with the same unhashable type: 'list' error.
Exercise
A class defines __eq__ comparing self.id, but no __hash__. You try to add an instance to a set. What happens, and how do you fix it?
Show answer
It raises TypeError: unhashable type, because defining __eq__ without __hash__ sets __hash__ to None. Fix it by adding def __hash__(self): return hash(self.id) and not changing id after the object is stored.