Sub topic 13
How hash tables give fast lookups
This chapter explains why d[key] takes about the same time in a dictionary of ten entries as in one of ten million. It assumes you know how to create, read and change dictionaries, what hashable means, and the difference between mutable and immutable objects. It also assumes you are comfortable reading short classes with __eq__ and __hash__ methods. The details below describe CPython, the reference implementation. Other interpreters differ in the internals but not in the guarantees.
The problem a hash table solves
A list finds a value by scanning. Searching for "pear" in a list of a million strings may compare against all of them. A sorted list with binary search needs about 20 comparisons for a million items, but it must stay sorted, so inserting is slow.
A hash table skips the search. It turns the key into an integer, uses that integer to compute a position in an array, and looks there first. Lookup, insertion and deletion are therefore O(1) on average. That means the cost does not grow with the number of entries.
Step 1: the hash function
hash(obj) returns an integer for any hashable object. The rule that makes the whole design work is the hash contract:
- If
a == b, thenhash(a) == hash(b). - The hash of an object must not change during its lifetime.
The reverse is not required. Two unequal objects may share a hash. That situation is a collision, covered below.
print(hash(1) == hash(1.0) == hash(True)) # True
print(hash((1, 2)) == hash((1, 2))) # True
d = {1: "int"}
d[1.0] = "float" # 1 == 1.0, so this is the same key
print(d) # {1: 'float'}
print(d[True]) # floatThe contract is the reason 1, 1.0 and True act as one key. They compare equal, so they must hash equal, so they land in the same place.
String hashes behave differently from integer hashes. Python seeds the hash of str and bytes randomly for each process, as a defence against attacks that craft colliding keys. hash("apple") therefore changes between runs unless you set the PYTHONHASHSEED environment variable. Never store a string hash and expect it to stay valid.
Step 2: from hash to slot
CPython keeps a table whose number of slots is a power of two, such as 8, 16 or 32. It maps the hash to a slot with a bit mask, which is a fast form of the remainder operation:
slot = hash & (table_size - 1)Inspecting that slot gives one of three outcomes:
- The slot is empty. The key is not in the dictionary.
- The slot holds the key you want. It matches if the stored key is the same object, or has the same stored hash and compares equal with
==. - The slot holds a different key. This is a collision, and the lookup must try another slot.
Step 3: collisions and probing
With far more possible hashes than slots, collisions are certain. CPython uses open addressing: every entry lives directly in the table, and a collision is resolved by following a deterministic sequence of other slots until the key or an empty slot appears. The sequence uses the whole hash, not just the low bits. Each step shifts in more of the hash, so keys that collide at first soon follow different paths.
The == comparison runs only when the stored hash matches the lookup hash, or when the objects are identical. This keeps expensive __eq__ calls rare.
Step 4: keeping the table sparse
Probing is fast only while the table has plenty of empty slots. CPython resizes the table when it becomes about two-thirds full. Resizing allocates a larger table and reinserts every entry. That single operation is O(n), but it happens after exponentially more insertions each time, so the cost spread over all insertions is O(1) per insertion. This is called amortized constant time.
Deleting an entry does not shrink the table. The slot is marked as deleted so that probe sequences passing through it still work, and the space returns only on the next resize.
The compact layout and insertion order
Before Python 3.6, a dictionary was one sparse array of (hash, key, value) records, and iteration order followed the slot positions. Modern CPython splits the structure in two:
- An index table, sparse and made of small integers, either empty or pointing into the entries array.
- An entries array, dense, holding (hash, key, value) records in the order they were inserted.
A lookup hashes into the index table, reads the entry number, and then checks that entry. This layout saves memory because the sparse part stores only small integers. It also explains why dictionaries remember insertion order: iteration walks the dense entries array from the start. The language has guaranteed this order since Python 3.7.
A toy hash table
The class below implements the ideas above in simplified form: it hashes, masks, probes linearly, and resizes at two-thirds load. It has no deletion, which keeps it short.
class ToyDict:
def __init__(self):
self._size = 8
self._slots = [None] * self._size
self._used = 0
def _find(self, key):
i = hash(key) % self._size
while self._slots[i] is not None:
stored_key, _ = self._slots[i]
if stored_key is key or stored_key == key:
return i
i = (i + 1) % self._size
return i # first empty slot on the probe path
def __setitem__(self, key, value):
i = self._find(key)
is_new = self._slots[i] is None
self._slots[i] = (key, value)
if is_new:
self._used += 1
if self._used * 3 >= self._size * 2:
self._resize()
def __getitem__(self, key):
slot = self._slots[self._find(key)]
if slot is None:
raise KeyError(key)
return slot[1]
def _resize(self):
entries = [s for s in self._slots if s is not None]
self._size *= 2
self._slots = [None] * self._size
self._used = 0
for key, value in entries:
self[key] = value
t = ToyDict()
for i in range(20):
t[f"k{i}"] = i
print(t["k7"]) # 7
print(t._size) # 32
try:
t["missing"]
except KeyError as exc:
print("KeyError", exc) # KeyError 'missing'The loop in _find ends because the table never fills past two-thirds, so an empty slot always exists. The table doubles from 8 to 16 at 6 entries and to 32 at 11 entries, so 20 entries end in 32 slots.
When fast lookups become slow
The O(1) claim is an average, and it depends on the hash function spreading keys out. If many keys share a hash, every operation must walk the same long probe path and call __eq__ along the way. In the worst case, lookup degrades to O(n). The next example counts __eq__ calls for a well-behaved hash and for a constant one.
class Key:
eq_calls = 0
def __init__(self, n, constant_hash):
self.n = n
self.constant_hash = constant_hash
def __hash__(self):
return 1 if self.constant_hash else hash(self.n)
def __eq__(self, other):
Key.eq_calls += 1
return self.n == other.n
def count_eq_calls(constant_hash):
Key.eq_calls = 0
d = {}
for n in range(500):
d[Key(n, constant_hash)] = n
return Key.eq_calls
good = count_eq_calls(False)
bad = count_eq_calls(True)
print(good == 0) # True: distinct hashes never trigger __eq__
print(bad > 100_000) # True: roughly n*(n-1)/2 comparisonsThis is also why Python randomizes string hashes. Without randomization, an attacker who knows the hash function could send a web service many keys that collide and make each request cost quadratic time.
Rules for your own key classes
The mechanism explains each rule you may have memorized.
| Situation | Consequence |
|---|---|
| Key's hash changes after insertion | The entry sits in a slot the new hash no longer points to, so lookups miss it. |
| `__eq__` defined, `__hash__` not | Python sets `__hash__` to `None` and instances become unhashable. |
| Equal objects with different hashes | Equal keys land in different slots and appear as separate keys. |
| Hash computed from mutable fields | Mutating the object after insertion breaks the first row's guarantee. |
| Lists, dicts and sets as keys | They are unhashable because they are mutable, so `TypeError` is raised. |
A safe pattern is to compute the hash from the same immutable fields that __eq__ compares. A frozen dataclass or a named tuple does this for you:
from dataclasses import dataclass
@dataclass(frozen=True)
class Point:
x: int
y: int
visits = {Point(1, 2): "home"}
print(visits[Point(1, 2)]) # homePerformance summary
| Operation | Average | Worst case | Note |
|---|---|---|---|
| `d[key]`, `key in d` | O(1) | O(n) | Worst case needs heavy collisions. |
| `d[key] = value` | O(1) amortized | O(n) | A resize copies every entry. |
| `del d[key]` | O(1) | O(n) | Does not shrink the table. |
| Iteration | O(n) | O(n) | Walks the dense entries array. |
| `value in d.values()` | O(n) | O(n) | Values are not hashed for lookup. |
The last row is a common mistake. Only keys are indexed. To search by value often, build a second dictionary that maps values back to keys.
Hash tables spend memory to buy speed. A dictionary of small integers uses several times the memory of a list of the same length. Use a dictionary when you look things up by key, and a list or tuple when you only iterate in order.
Exercise
A class defines __eq__ to compare two fields, and __hash__ to return hash(self.id), where id is one of those fields. Does this satisfy the hash contract? What goes wrong if __hash__ instead returns id(self), the object's memory address?
Show answer
It satisfies the contract. Equal objects have equal fields, including id, so their hashes are equal. Different objects may share an id and collide, which is allowed. Returning the memory address breaks the contract. Two distinct objects that compare equal have different addresses, so they hash differently, land in different slots, and a lookup with an equal but separate object misses.
Exercise
Using only what this chapter describes, explain why d = {}; d[1] = "a"; d[1.0] = "b" leaves d with one entry, and say which value it holds.
Show answer
1 == 1.0, so hash(1) == hash(1.0). Both keys map to the same slot, and the equality check finds the existing key. The second assignment replaces the value and keeps the original key 1. The dictionary is {1: 'b'}.
Exercise
A program deletes most entries from a huge dictionary and memory use barely drops. Why, and what is a simple way to release the memory?
Show answer
Deletion marks slots as removed but does not shrink the table. The space returns only when a resize happens. Building a fresh dictionary from the survivors, such as d = dict(d) or a comprehension, allocates a table sized to the remaining entries. The old table is then freed.