The Python FAQ sums it up: CPython's dictionaries are hash tables that resize. Here is what happens inside one, in CPython 3.12.
A dict keeps its entries in order, and their positions in a table
Predict
A dict gets the keys 12, 33, 7 and 42, in that order. In what order does list(d) give them back?
d = {12: "a", 33: "b", 7: "c", 42: "d"}print(list(d))
[12, 33, 7, 42]
The keys come back in the order you added them. That's because a dict keeps two arrays:
The table of 8 slots: each holds an entry's number
slots
012345671302
Entry
Hash
Key
Value
0
12
12
'a'
1
33
33
'b'
2
7
7
'c'
3
42
42
'd'
The entries array holds each hash, key and value, in the order they were added. Walking a dict walks this array, so it comes out in insertion order.
The table is an array of 2i slots, 2 to the power i. Each slot holds the position of an entry, or is empty. The first key you add gets the dict a table of 8 slots.
A lookup computes hash(key) and takes its last i bits as the first slot to look at. An empty slot means the key isn't there. A slot that points to an entry gets checked:
The very same object is an instant match.
Otherwise the stored hash must equal the new one, before Python pays for ==.
Only a match ends the search.
A set is a similar hash table without the values, and it doesn't keep insertion order.
Two bit operators do this work. a & b keeps only the bits set in both numbers. With 8 slots, slots - 1 is 7, 0b111 in binary, so hash(key) & 7 keeps the hash's last three bits: a number from 0 to 7, the same as % 8 for a hash that isn't negative. a >> n shifts the bits right by n places: 26 >> 2 is 6, since 0b11010 becomes 0b110.
In the editor, write compact(keys, slots): the two arrays for a few integer keys. entries holds each key once, in the order first added. table starts all None, and slot hash(key) & (slots - 1), the hash's last bits, holds the key's entry number.
Pick an answer above to see the rest
Instructions
1
Write compact(keys, slots): entries holds each key once, in the order first added, and table has slots places, all None at first.
2
Put each new key's entry number in table[hash(key) & (slots - 1)]. The keys in the tests never collide.