26/40
Part 5 of 7 · Inside a dictLearn and do

A collision probes other slots by a fixed rule

When the slot holds a different key, CPython probes another slot. The next slot comes from the slot it just tried and from the hash's higher bits, which it feeds in a few at a time. Here's a model of that rule, small enough to run by hand on the integer keys from the start of the lesson:

# 8 slots
def slot_for(key, table, mask=7):
    h = hash(key)
    i, perturb = h & mask, h
    while table[i] is not None:
        perturb >>= 5
        i = (i * 5 + perturb + 1) & mask
    return i


table = [None] * 8
for key in (12, 33, 7, 42, 26):
    table[slot_for(key, table)] = key
print(table)
[None, 33, 42, 26, 12, None, None, 7]
Predict

With 8 slots, a key starts at slot hash & 7. Which slot does 26 want first?

Pick an answer above to see the rest