Kodewick
Start learning →
Open addressing: how dict does it19 / 52

Open addressing: how dict does it

Lesson 19 of 52 · Part 4 · Hash tables: dict and set · about 20 minutes

Open addressing keeps every key in one row of slots and, when a key's slot is taken, tries further slots by a fixed rule until one is free; a deletion leaves a tombstone so other keys stay findable, and CPython's dict works this way, growing at 2/3 full.

Python programs are full of dicts: a module's globals, an object's attributes and keyword arguments are all dicts underneath. They must be fast and small, so CPython does not hang a chain off each slot; it keeps every key in one row of slots. If the slot a key works out to is taken, it tries another slot by a fixed rule until it finds a free one. This is open addressing: a key does not necessarily live in the slot it works out to. This lesson first writes the simplest rule (try the next slot) by hand on an 11-slot list and counts every probe, then looks at what dict really does.

Linear probing: putting a key in

The rule: start at key % m; if that slot is taken, look at the next one (wrapping round to 0 at the end) until a free slot turns up. Put in 22 41 53 46 30 13 1 67 in turn:

table (indexes 0–10)012345678910
1i = key % m2while table[i] is not None:3    i = (i + 1) % m4table[i] = key

Linear probing, table size 11: if the slot worked out is taken, try the next one; in the end 0–4 have joined into one block
main.py
1m = 112table = [None] * m3 4def put(key):5    i = key % m6    probes = 17    while table[i] is not None:8        i = (i + 1) % m9        probes += 110    table[i] = key11    return i, probes12 13total = 014for k in [22, 41, 53, 46, 30, 13, 1, 67]:15    i, p = put(k)16    total += p17    print(f"{k:2} goes in slot {i:2}, {p} probes")18print(table)19print("probes in all:", total)
Output
22 goes in slot  0, 1 probes
41 goes in slot  8, 1 probes
53 goes in slot  9, 1 probes
46 goes in slot  2, 1 probes
30 goes in slot 10, 3 probes
13 goes in slot  3, 2 probes
 1 goes in slot  1, 1 probes
67 goes in slot  4, 4 probes
[22, 1, 46, 13, 67, None, None, None, 41, 53, 30]
probes in all: 14

That last step is linear probing's weakness, called clustering: in a block of taken slots, anything that lands inside walks to the end of the block and takes that slot too, so the block keeps growing. 67 works out to 1 and has nothing to do with 13 or 46, yet they push it all the way to slot 4.

Choose one

Table size 7, linear probing, and the keys 5, 12, 19 go in, in that order. Which slot does 19 end up in?

Finding: the same path, up to a free slot

Finding walks exactly the path storing walked: start at key % m and move one slot at a time. Meet the key and it is found; meet a free slot and it is not in the table (if it were, storing would have stopped at this free slot).

main.py
1m = 112table = [22, 1, 46, 13, 67, None, None, None, 41, 53, 30]3 4def find(key):5    i = key % m6    probes = 17    while table[i] is not None:8        if table[i] == key:9            return i, probes10        i = (i + 1) % m11        probes += 112    return -1, probes13 14print(find(22))      # in the slot it works out to: 1 probe15print(find(67))      # 1 → 2 → 3 → 416print(find(12))      # 12 % 11 = 1, walks all the way to the free slot 5 before saying no17print(find(5))       # slot 5 itself is free: 1 probe
Output
(0, 1)
(4, 4)
(-1, 5)
(-1, 1)

A miss costs more than a hit: a hit stops at the key, a miss walks until a free slot. That is why the table must never fill up: with no free slot at all, looking for a missing key would go round forever.

Choose one

In this stage's table (slots 0–4 hold 22 1 46 13 67, slots 5–7 are empty, slots 8–10 hold 41 53 30), how many slots does a search for 35 look at before it knows 35 isn't there?

Exercise 1

Finding with linear probing

Finish find(table, key): start at key % m and walk one slot at a time; when found, return (index, probes); a None means it is not there, so return (-1, probes).

It should print
(0, 1)
(4, 4)
(10, 3)
(-1, 5)
exercise1.py
1m = 112table = [22, 1, 46, 13, 67, None, None, None, 41, 53, 30]3 4def find(table, key):5    # i starts at key % m; each slot looked at is one more probe6    return -1, 07 8print(find(table, 22))9print(find(table, 67))10print(find(table, 30))11print(find(table, 12))
Output
Press Run or Ctrl+Enter

Deleting: leave a tombstone

To delete a key, the obvious idea is to set its slot back to None. But finding stops at the first free slot, so clearing a slot cuts the path of other keys:

table (indexes 0–10)221461367415330012345678910

The wrong way: clear slot 9 and 30 can no longer be found; leaving a tombstone † is right
main.py
1m = 112TOMB = "†"                       # a tombstone: a slot that was deleted3 4def find(table, key):5    i = key % m6    while table[i] is not None:  # a tombstone is not None: walk past it7        if table[i] == key:8            return i9        i = (i + 1) % m10    return -111 12def delete_wrong(table, key):13    i = find(table, key)14    if i >= 0:15        table[i] = None16 17def delete(table, key):18    i = find(table, key)19    if i >= 0:20        table[i] = TOMB21 22t = [22, 1, 46, 13, 67, None, None, None, 41, 53, 30]23delete_wrong(t, 53)24print("find 30 after clearing:", find(t, 30))25 26t = [22, 1, 46, 13, 67, None, None, None, 41, 53, 30]27delete(t, 53)28print("find 30 after a tombstone:", find(t, 30))29print("find 53 again:", find(t, 53))30print(t)
Output
find 30 after clearing: -1
find 30 after a tombstone: 10
find 53 again: -1
[22, 1, 46, 13, 67, None, None, None, 41, '†', 30]

To finding, a tombstone is "not a free slot"; to inserting, it can be reused (a new key may take it). But many tombstones mean finding walks over many dead slots, so a resize moves only the live keys and drops every tombstone. CPython calls tombstones dummies and does the same.

Choose one

After deleting with tombstones, which statement is true?

Guess the outputA wrong guess is fine

3, 10 and 17 all leave remainder 3 when divided by 7; linear probing put them in slots 3, 4 and 5. First 3 is deleted with a tombstone, then 24 goes in (24 % 7 = 3). What does it print?

1m = 72TOMB = "†"3table = [None, None, None, 3, 10, 17, None]4 5def find(key):6    i = key % m7    while table[i] is not None:8        if table[i] == key:9            return i10        i = (i + 1) % m11    return -112 13def put(key):14    i = key % m15    while table[i] is not None and table[i] != TOMB:16        i = (i + 1) % m17    table[i] = key18 19table[find(3)] = TOMB20put(24)                                        # 24 % 7 = 321print(find(24), find(17))
Exercise 2

Deleting with a tombstone

Right now delete sets the slot back to None, and after deleting 46 neither 13 nor 67 can be found. Make it leave the tombstone TOMB so the keys after it can still be found. find needs no change: a tombstone is not None, so it walks past.

It should print
True False
3 4 -1
[22, 1, '†', 13, 67, None, None, None, 41, 53, 30]
exercise2.py
1m = 112TOMB = "†"3table = [22, 1, 46, 13, 67, None, None, None, 41, 53, 30]4 5def find(table, key):6    i = key % m7    while table[i] is not None:8        if table[i] == key:9            return i10        i = (i + 1) % m11    return -112 13def delete(table, key):14    i = find(table, key)15    if i < 0:16        return False17    table[i] = None          # wrong: cuts the path to 13 and 6718    return True19 20print(delete(table, 46), delete(table, 46))21print(find(table, 13), find(table, 67), find(table, 46))22print(table)
Output
Press Run or Ctrl+Enter

Load factor and resizing

The load factor α = the number of keys n ÷ the number of slots m. The larger α, the fewer free slots, and the further each search walks. On a 503-slot table, put in different numbers of keys (a run of numbers that looks scrambled but is the same on every run) and count the average probes:

main.py
1def make_keys(n):2    keys, x = [], 73    for _ in range(n):4        x = (x * 1103515245 + 12345) % 21474836485        keys.append(x)6    return keys7 8def trial(m, n):9    table = [None] * m10    hit = 011    for k in make_keys(n):12        i = k % m13        hit += 114        while table[i] is not None:15            i = (i + 1) % m16            hit += 117        table[i] = k18    miss = 019    for start in range(m):           # from every slot, look for a key that is not there20        i = start21        miss += 122        while table[i] is not None:23            i = (i + 1) % m24            miss += 125    return hit / n, miss / m26 27m = 50328for alpha in [0.25, 0.5, 0.75, 0.9]:29    n = int(alpha * m)30    hit, miss = trial(m, n)31    print(f"α = {alpha:.2f}: a hit takes {hit:.1f} probes on average, a miss {miss:.1f}")
Output
α = 0.25: a hit takes 1.1 probes on average, a miss 1.4
α = 0.50: a hit takes 1.4 probes on average, a miss 2.4
α = 0.75: a hit takes 2.1 probes on average, a miss 6.9
α = 0.90: a hit takes 4.0 probes on average, a miss 36.0
αHitMissIn theory (hit / miss)
0.25about 1.1about 1.41.2 / 1.4
0.5about 1.4about 2.41.5 / 2.5
0.75about 2.1about 6.92.5 / 8.5
0.9about 4.0about 365.5 / 50.5

Linear probing's theory says ½(1 + 1/(1 − α)) and ½(1 + 1/(1 − α)²): at α = 0.9, a miss walks dozens of slots, and it gets worse quadratically. That is the price of clustering. So an open-addressing table grows before it is full: once α crosses a line (2/3 in CPython), it moves to a table twice as big and works out every live key's slot again for the new m.

main.py
1def make_keys(n):2    keys, x = [], 73    for _ in range(n):4        x = (x * 1103515245 + 12345) % 21474836485        keys.append(x)6    return keys7 8class LinearTable:9    def __init__(self):10        self.slots = [None] * 811        self.n = 012        self.moves = 013 14    def _place(self, key):15        m = len(self.slots)16        i = key % m17        while self.slots[i] is not None:18            i = (i + 1) % m19        self.slots[i] = key20 21    def add(self, key):22        m = len(self.slots)23        if (self.n + 1) * 3 > m * 2:          # this key would pass 2/3: grow first24            old = self.slots25            self.slots = [None] * (m * 2)26            for k in old:27                if k is not None:28                    self._place(k)            # work out the slot again for the new size29                    self.moves += 130            print(f"key {self.n + 1:3}: {m} slots → {m * 2}, moved {self.n}")31        self._place(key)32        self.n += 133 34t = LinearTable()35for k in make_keys(100):36    t.add(k)37print("stored", t.n, "keys, moved", t.moves, "times in all")
Output
key   6: 8 slots → 16, moved 5
key  11: 16 slots → 32, moved 10
key  22: 32 slots → 64, moved 21
key  43: 64 slots → 128, moved 42
key  86: 128 slots → 256, moved 85
stored 100 keys, moved 163 times in all

Every resize moves all the keys, but the size doubles, so the moves add up to 5 + 10 + 21 + 42 + 85 = 163, under 2n: just like list's append, amortised O(1).

Choose one

From the table this stage measured: as α goes from 0.5 to 0.9, how does the average number of probes for a key that isn't there change, roughly?

Choose one

This stage's LinearTable starts with 8 slots and grows first whenever the new key would push it past 2/3. Which key triggers the first resize?

CPython's dict

CPython's dict and set are open addressing, with three refinements over the linear probing written by hand in this lesson.

The table size is a power of two (at least 8), the slot is hash & (m - 1), faster than %, and the table grows at 2/3 full.

Probing doesn't step one slot at a time; it gradually mixes in the hash's higher bits. Two keys that collide on their first slot then take different paths, so they don't pile up in a block as linear probing does:

main.py
1def probes(h, m, count):2    mask = m - 13    perturb = h4    i = h & mask5    out = [i]6    while len(out) < count:7        perturb >>= 5                       # mix in a few more high bits each time8        i = (i * 5 + perturb + 1) & mask9        out.append(i)10    return out11 12print(12345 & 7, 12353 & 7)                 # both keys start at slot 113print(probes(12345, 8, 6))14print(probes(12353, 8, 6))15print([(1 + j) % 8 for j in range(6)])      # linear probing: both take this path
Output
1 1
[1, 7, 0, 1, 6, 7]
[1, 0, 5, 2, 3, 0]
[1, 2, 3, 4, 5, 6]

After a few shifts perturb becomes 0 and only i * 5 + 1 is left, which in a power-of-two table visits every slot, so a free slot is always found if there is one.

Compact storage keeps insertion order. A slot holds not the key but a small number; the keys, values and hashes go one row after another into a second table, the entries, in the order they were put in:

 201    
01234567
↑10 % 8 = 2↑3 % 8 = 3↑17 % 8 = 1a free slot takes 1 byte
The index table of d = {10: "a", 3: "b", 17: "c"}: 8 slots, each holding a row number in the entries, not the key itself
RowHashKeyValue
01010'a'
133'b'
21717'c'
The entries grow in the order keys were put in: walking a dict reads this table top to bottom, so the order is insertion order

A free slot in the index table takes just 1 byte (while the table is small), far less than storing "hash, key, value" at 8 bytes each in every slot. Iteration reads the entries, so since Python 3.7 a dict is guaranteed to iterate in insertion order. A set has no entries layer, so it iterates slot by slot:

main.py
1d = {10: "a", 3: "b", 17: "c"}2s = {10, 3, 17}3print(list(d))4print(list(s))
Output
[10, 3, 17]
[17, 10, 3]
Guess the outputA wrong guess is fine

Delete 5, then put it back. What does it print?

1d = {5: "a", 9: "b"}2d[1] = "c"3del d[5]4d[5] = "d"5print(list(d))

In interviews: "Why is dict O(1)?", "What happens on a collision?", "Why can't deletion just clear the slot?" and "Why does dict have an order?" are all in this lesson. When you say O(1), say on average: the load factor stays under 2/3 and the hash spreads evenly; in the worst case (every key with the same hash) it is O(n).

Choose one

Why does CPython's dict iterate in insertion order?

How you write it at work

dict and set are ready-made open-addressing tables; you don't write your own. A few things to know:

main.py
1d = {1: "a", 2: "b", 3: "c", 4: "d"}2try:3    for k in d:4        if k % 2 == 1:5            del d[k]6except RuntimeError as e:7    print("RuntimeError:", e)8 9d = {1: "a", 2: "b", 3: "c", 4: "d"}10for k in list(d):                  # copy the keys first, then change d11    if k % 2 == 1:12        del d[k]13print(d)14 15d = {1: "a", 2: "b", 3: "c", 4: "d"}16print({k: v for k, v in d.items() if k % 2 == 0})
Output
RuntimeError: dictionary changed size during iteration
{2: 'b', 4: 'd'}
{2: 'b', 4: 'd'}
  • Don't add or delete keys while iterating: the table may grow and the entries may change, so Python stops with an error. Copy the keys first with list(d), or build a new dict with a comprehension. Changing the value of an existing key is fine.
  • Where order matters, use a dict, not a set: a dict keeps insertion order; a set's order follows its slots, and string slots change from run to run. To deduplicate in order, write list(dict.fromkeys(xs)).
  • A dict that only shrinks doesn't get smaller: the tombstones and the emptied entries stay. After deleting most of it, d = dict(d) builds a new compact one.
  • Costs: d[k], k in d, d[k] = v and del d[k] are O(1) on average; the one resize is O(n), still O(1) amortised; len(d) is O(1), it is stored.
Guess the outputA wrong guess is fine

Copy the keys first, then delete, then set one value. What does it print?

1d = {"a": 1, "b": 2, "c": 3}2for k in list(d):3    if d[k] > 1:4        del d[k]5d["b"] = 56print(d)

Summary

Take-away

Open addressing: one row of slots, try another on a collision

  • Linear probing: from key % m, step one slot at a time to a free one; finding walks the same path and gives up only at a free slot
  • Deleting leaves a tombstone: clearing the slot cuts other keys' paths
  • Load factor α = n / m; linear probing clusters and slows as α rises, so at 2/3 full the table doubles and every slot is worked out again
  • CPython's dict: power-of-two sizes, perturb probing that mixes in high bits, entries stored in insertion order
1i = key % m2while table[i] is not None:3    i = (i + 1) % m4table[i] = key5for k in list(d): ...   # deleting while iterating: copy the keys first