Load factor
A table of m = 4 buckets, each holding a list called a chain. put sends key k to bucket h(k) % m. For small whole numbers, Python's hash(k) is k itself. Put 5, 12, 9 and 2: 5 and 9 both pick bucket 1.
The load factor α = n/m counts keys per bucket: here 4/4 = 1. It is the average chain length. If keys spread evenly, a search walks about 1 + α entries, so a small α keeps lookups fast.
Resizing
Now put 7. Line 2 checks first: n == m, so every bucket already holds one key on average. One more key would push α above 1, so put calls grow before 7 goes in.
grow lifts every key out into a list, doubles m to 8, then puts each key back at h(k) % 8. 12 moves to bucket 4 and 5 to bucket 5; 9 and 2 stay. Then 7 lands in bucket 7: α = 5/8.
A grow touches all n keys, so it costs O(n). But doubling means the next grow waits until n more keys arrive. Over N puts, grows move fewer than 2N keys in total: O(1) per put on average, or amortised.
Universal hashing
Anyone who knows h(k) = k can pick keys that leave the same remainder: 3, 11, 19, 27 and 35 all give k % 8 = 3. One chain of 5: a search walks every key, though α is only 5/8.
Pick h at random when the table is made: h(k) = ((a·k + b) % 37) % m, with a prime 37 above every key and random a, b below it (a ≠ 0). This draw, a = 4, b = 9, spreads the keys.
The family is universal: two different keys share a bucket in at most 1/m of the draws. The worst pair here collides in 136 of 1332. So a key's chain holds at most 1 + (n − 1)/m = 1.5 keys on average.
What happens
;; step 1/8 · chains h(k) = hash(k) = k (hash(5) == 5 in Python) put 5: 5 % 4 = 1 put 12: 12 % 4 = 0 put 9: 9 % 4 = 1 put 2: 2 % 4 = 2 bucket 0: [12] bucket 1: [5, 9] bucket 2: [2] bucket 3: []
The figure uses whole-number keys, h(k) = hash(k) = k and h(k) % m, as in the division method of MIT 6.006 Lecture 4. Python's hash() of a small int is the int itself; real dicts mix the bits further and use open addressing instead of chains. H(p, m) = { ((a·k + b) mod p) mod m : a in 1..p−1, b in 0..p−1 } with a prime p above every key is universal (MIT 6.006 Lecture 4; CLRS §11.3). The figure checks it for p = 37, m = 8 over every pair of keys and every draw.