Sub topic 11
Choosing keys: equality, hashing, and immutability
This chapter assumes you have read the earlier chapters on hash functions, bucket indexes, and collisions. It also assumes you can read basic Python classes. Python is used here because its dict enforces these rules in a visible way.
A hash table does not store keys by position. It finds them by computing a number from the key and then comparing keys for equality. That makes the key type part of the table's correctness. A bad key type does not slow the table down. It makes lookups return the wrong answer.
The two operations a key must support
Every lookup uses two operations on the key:
- Hashing turns the key into an integer. The table reduces this integer to a bucket index, for example
hash(key) % len(buckets). - Equality compares the probe key with each stored key in that bucket (or in the probe sequence). The hash only narrows the search to a few candidates. Equality decides which candidate is the match.
The diagram shows where each operation is used.
The consistency rule
One rule ties the two operations together:
- If
a == b, thenhash(a) == hash(b).
The reverse is not required. Two unequal keys may share a hash, and that is just a collision, which the table already handles. Two equal keys with different hashes break the table. They land in different buckets, so the lookup never reaches the stored entry.
The following class breaks the rule on purpose. Two Num objects are equal when their values match modulo 10, but the hash uses the raw value.
class Num:
def __init__(self, n):
self.n = n
def __eq__(self, other):
return isinstance(other, Num) and self.n % 10 == other.n % 10
def __hash__(self):
return hash(self.n) # wrong: equal objects can hash differently
d = {Num(3): "stored"}
print(Num(3) == Num(13)) # True
print(d.get(Num(13))) # None, because 13 lands in a different slot than 3Equal keys should find the same entry, but Num(13) looks in the wrong place. The fix is to hash exactly the data that equality uses:
class Num:
def __init__(self, n):
self.n = n
def __eq__(self, other):
return isinstance(other, Num) and self.n % 10 == other.n % 10
def __hash__(self):
return hash(self.n % 10)
d = {Num(3): "stored"}
print(d.get(Num(13))) # storedOverriding equality removes the default hash
In Python 3, a class that defines __eq__ without defining __hash__ becomes unhashable. The language does this to stop you from keeping the old identity-based hash alongside a new value-based equality, which would violate the rule.
class Pair:
def __init__(self, a, b):
self.a = a
self.b = b
def __eq__(self, other):
return isinstance(other, Pair) and (self.a, self.b) == (other.a, other.b)
try:
{Pair(1, 2): "x"}
except TypeError as e:
print(e) # unhashable type: 'Pair'Other languages handle this differently. Java does not stop you from overriding equals without hashCode, so the bug shows up only as lookups that fail at run time. Treat the two methods as a pair in every language.
Why keys must be immutable
The table computes a key's hash once, when the entry is stored, and uses it to place the entry. If the key later changes in a way that changes its hash or its equality, the entry stays in its old bucket while lookups look in a new one.
class Box:
def __init__(self, v):
self.v = v
def __eq__(self, other):
return isinstance(other, Box) and self.v == other.v
def __hash__(self):
return hash(self.v)
b = Box(1)
d = {b: "found"}
b.v = 2
print(d.get(b)) # None: hash is now 2, but the entry sits where hash 1 put it
print(d.get(Box(1))) # None: the right bucket, but the stored key no longer equals Box(1)
print(len(d)) # 1: the entry still exists but is unreachableThe entry is still in the table, yet neither the old value nor the new value can find it. It also cannot be removed, and it takes up space until the table is rebuilt.
This is why built-in mutable containers such as list, dict, and set are rejected as keys. Python refuses to hash them, which turns a silent corruption bug into an immediate error.
A frozen dataclass is a simple way to get a value-based, immutable key. It generates matching __eq__ and __hash__ methods from its fields, and it blocks assignment after construction.
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)Common key types
| Key type | Usable as a key? | Notes |
|---|---|---|
| `int`, `str`, `bytes` | Yes | Immutable, with value-based equality. |
| `tuple` of hashable items | Yes | Hashable only if every element is hashable. |
| `frozenset` | Yes | Use it when the key is an unordered group. |
| Frozen dataclass | Yes | Equality and hash come from the fields. |
| `list`, `dict`, `set` | No | Mutable, so Python raises `TypeError`. |
| Plain class, no `__eq__` | Yes | Equality and hash use object identity, not contents. |
| `float` | With care | See the next section. |
A plain class with no overrides is a legal key, but two instances with the same fields are different keys. That is correct for "this specific object" and wrong for "any object with these values".
Edge cases with numbers
Numeric types follow the consistency rule across types, which sometimes surprises people:
d = {1: "int"}
print(d[1.0]) # int, because 1 == 1.0 and their hashes match
print(d[True]) # int, because True == 1 and hash(True) == 1
d[1.0] = "float"
print(d) # {1: 'float'}: same key, the value was replaced, the original key object was keptFloating-point keys have a harder problem. 0.1 + 0.2 == 0.3 is False, so computed floats rarely match a stored float. Prefer integers (for example, cents instead of dollars) or round to a fixed precision before using a number as a key.
NaN breaks the equality contract itself, because float("nan") != float("nan"). Python's dict first checks whether the two keys are the same object, so a stored NaN is found only by the identical object:
nan = float("nan")
d = {nan: "x"}
print(d[nan]) # x, found by identity
print(float("nan") in d) # False, a different NaN objectAvoid NaN as a key.
Hash stability
The hash must not change while the key is in the table, and equal keys must produce equal hashes within one table. Nothing requires the hash to stay the same between program runs. Python randomizes string hashes per process (this is the defense described in the chapter on hash flooding), so hash("apple") differs from run to run. Never write hash values to disk or use them as permanent identifiers. For that purpose, use a stable function such as a cryptographic digest.
Choosing a key: a checklist
- Decide what makes two keys "the same" in your problem. That decision defines equality.
- Hash exactly the fields that equality compares, and no others.
- Make those fields immutable, deeply.
- Prefer small keys. Hashing and comparing cost time proportional to the key's size, so a long string key makes every operation slower than the "constant time" figure suggests.
- Avoid floats and
NaNunless you control the rounding.
Exercise
A class Version defines __eq__ to compare (major, minor), and defines __hash__ as hash((self.major, self.minor, self.patch)). Two versions with the same major and minor but different patch numbers are therefore equal. What goes wrong when they are used as dictionary keys, and how do you fix it?
Show answer
The rule "equal objects must have equal hashes" is violated. Two equal versions with different patch numbers hash to different values, so they usually land in different buckets. A lookup with one of them can miss an entry stored under the other, even though they compare equal. The fix is to hash only the fields that equality uses: hash((self.major, self.minor)). If the patch number should distinguish keys, include it in __eq__ as well. Also make the fields immutable, for example with a frozen dataclass, so that the hash cannot change after the object is stored.