Sub topic 11
Choosing keys: equality, hashing, and immutability
This chapter assumes you can write Python classes and functions. It also assumes you know how a hash table maps a key to a bucket and how chaining or probing resolves collisions. Here we look at what a key must do for that machinery to work.
The consistency rule
A hash table finds an entry in two steps. It hashes the key to pick a bucket, then compares keys with == inside that bucket. Both steps must agree. The rule is:
- If
a == b, thenhash(a) == hash(b).
The reverse is not required. Two unequal keys may share a hash, and that is only a collision. But two equal keys with different hashes break the table. They land in different buckets, so a lookup never compares them and the entry looks missing.
Immutability
The hash is computed when the key is stored. If the key changes afterward, its hash changes, but the entry stays in the old bucket. A lookup then goes to the wrong bucket and misses it.
For this reason Python rejects its mutable built-in containers as keys. Strings, numbers, and tuples of hashable items are safe, because they cannot change.
Making your own types usable
A frozen dataclass generates both __eq__ and a matching __hash__ from its fields. It also blocks assignment after creation, so the hash stays stable.
from dataclasses import dataclass
@dataclass(frozen=True)
class Point:
x: int
y: int
d = {Point(1, 2): "a"}
print(d[Point(1, 2)])
try:
d[[1, 2]] = "b"
except TypeError as e:
print(e)The first lookup succeeds even though Point(1, 2) is a new object, because the two points are equal and hash alike. The second statement raises TypeError: unhashable type: 'list'.
Common errors
Defining __eq__ without __hash__ is a frequent mistake. In Python, a class that defines __eq__ and not __hash__ has its __hash__ set to None, so its instances are unhashable. This is safer than silently inheriting an identity-based hash that disagrees with your equality.
The opposite mistake is hashing a field that equality ignores, or the reverse. Always hash exactly the fields that == compares, or a subset of them.
A third trap is a hash built from mutable state, such as a hand-written __hash__ that reads a field you later change.
Choosing keys in practice
| Key choice | Safe? | Reason |
|---|---|---|
| `"apple"` | Yes | Strings are immutable. |
| `(3, 4)` | Yes | A tuple of hashable items is hashable. |
| `([1], 2)` | No | The tuple contains a list, so hashing fails. |
| `frozenset({1, 2})` | Yes | It is the immutable form of a set. |
| `1` and `1.0` | Same key | They are equal and hash alike, so they share one entry. |
The last row shows the rule at work. Since 1 == 1.0, Python requires their hashes to match, so {1: "a", 1.0: "b"} holds one entry.
A good key is also cheap to hash and well distributed. A long string must be scanned in full to compute its hash, and a hash that returns the same value for many keys sends them all into one bucket. That turns the table into a list.
Exercise
A class defines __eq__ to compare only name, but its __hash__ combines name and age. Two objects have the same name and different ages. What goes wrong when you use them as dictionary keys, and how do you fix it?
Show answer
The objects are equal but have different hashes, which violates the consistency rule. They go to different buckets, so the table treats them as two entries, and a lookup with one may miss the other. Fix it by hashing only name, the field that equality compares, for example hash(self.name).
Exercise
Why can a tuple like (1, [2]) not be used as a dictionary key even though tuples are immutable?
Show answer
Hashing a tuple hashes each element. The list inside is unhashable, so hash raises a TypeError. The tuple is immutable in structure, but its contents can still change.