1def put(t, k):2 if t.n == t.m:3 grow(t)4 i = t.h(k) % t.m5 t.b[i].append(k)6 t.n += 1hash functionh(k) = hash(k) = knmα01234567512927311192735
Khaki blocks: keys, stacked into a chain on their bucketTrays: buckets 0 to 7 (4 until the table doubles)A hopping key: put, or a rehash after a growKeys stack on their bucket, so each stack is a chain and the load factor α = n/m is the average stack height. When n reaches m the table doubles and every key is lifted out and dropped into bucket h(k) % m again. Chosen keys pile onto one bucket under the fixed hash h(k) = k; a hash drawn at random from a universal family spreads them.

Load factor

  1. 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.

Resizing

Universal hashing

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.