Lesson · Python Internals
Dictionary & Set Internals
95 min readDictionary & Set Internals
Dictionaries and sets are hash-table-based collections. Hashes choose a probe path, equality resolves candidate matches, and resizing maintains expected constant-time operations.
Learning goals
- Trace a lookup through hash, probe, and equality, and say what each stage decides.
- Explain why two keys with identical hashes can coexist and how equality separates them.
- Show what insertion order promises and when deleting and reinserting changes a key's position.
- Explain what happens to a stored key when a field feeding its hash is mutated.
- Separate the language's promises about dicts and sets from CPython's table mechanics.
Mental model
The arrows are one lookup: the hash narrows the search, probing walks to candidate slots, and equality decides whether the candidate is the key you asked for. Sets reuse the same machinery with no values, and both structures resize when occupancy crosses a threshold, so the diagram describes the common case rather than every individual operation.
Hash points, probing walks, equality decides
equal hashes are not equal keys
Mental model
the same mechanism as a compact list
key → hash → probe sequence → candidate slot → equality
Core idea
A dict or set is a hash table: it converts a key into a slot index with hash, uses == to check the candidate it finds there, and probes when two keys want the same slot. The structure's performance rests on assumptions about the workload: hashes spread keys evenly, equality is cheap, and keys keep the hash they had when inserted, while occasional resizing keeps the table sparse enough to stay fast on average.
Hash tables
A hash table uses a hash value to narrow the search for a key, then uses equality to confirm a match. Collisions are normal and handled by the table's probing strategy.
Hashing
Hashing converts a key into an integer that a table turns into a starting slot; Python calls the key's __hash__ method, and objects that compare equal are required to produce the same hash. Hashes are not unique, so different keys can land on one value, and the table uses equality to finish the job. An object is usable as a dict key or set member only if it is hashable, which means its hash stays stable for as long as it is stored.
Collisions
Different keys can produce the same hash or probe position. A correct hash table resolves collisions and then uses equality to distinguish candidate keys.
Resizing
Hash tables resize to keep lookup behavior efficient as occupancy changes. Resizing can be expensive for one operation but supports good expected performance over many operations.
Insertion order
Modern Python dictionaries preserve insertion order as part of the language behavior. Updating an existing key does not normally move it to the end.
Mutable-key problems
If a key's hash or equality depends on fields you mutate after insertion, the table has stored it under a hash the object no longer produces; a later lookup computes a different probe path and fails to find the key even though it is still stored. The usual fixes are to key on immutable values, to use a snapshot of the relevant fields as the key, or to remove the entry, mutate, and reinsert.
Expected O(1) lookup
Expected constant-time lookup means the average amount of work per lookup does not grow with the number of stored entries: the hash narrows the search to a slot and equality checks a small number of candidates. The word expected carries the caveats, since collisions, resizing, and a poorly distributed hash can make individual operations cost more, while the average over many operations stays constant when keys spread evenly.
Walkthrough
aandbareKeyinstances with differentvaluefields but the sameforced_hash, so their hashes collide by construction; the custom__eq__says two keys match only when theirvaluefields are equal.mapping = {a: 10, b: 20}inserts both:bcannot take the slot its hash prefers becauseais already there, so probing moves it to the next usable slot, and the collision changes cost rather than correctness.mapping[a]andmapping[b]both start from the same slot; each lookup walks the candidate keys and uses__eq__to tell them apart, which is why the prints show 10 and 20.- Predict before running: what
len(mapping)would be if__eq__treated everyKeyas equal to every other (the second assignment would overwrite the first), and what would change if each instance had its own hash.
Experiments to try
- Change
b'sforced_hashto 2 and confirm the output is unchanged; explain why the collision was never required for correctness. - Call
hash(a)andhash(b)directly and compare the results withid(a)andid(b); state which value the dict actually uses for the first step. - Add a third key with the same hash and a new value, then print the dict, the key order, and
len(mapping); trace conceptually which slot the new key takes. - Delete
aand reinsert it (del mapping[a]thenmapping[a] = 99); print the key order and explain the new position with insertion order plus deletion behavior.
Playable lesson
Lab: Hash table explorer
Show key hashing, conceptual probing, equality checks, collisions, deletion markers, and resizing.
The lab should ask for a prediction before each state transition. Include a reset action and at least one intentionally misleading case.
Hash table explorer
Slot table
1 of 8 slots filled
Highlighted slots, in order: 3
Lookup
insert stored at slot 3
Equality checks
0
one per occupied slot visited
Predict first
The hash picked a slot that was empty. How many equality checks were needed?
`Key("a", 1)` is inserted. The hash narrows the search to one starting slot, and because that slot is empty there is nothing to compare, so the key goes straight in.
Common mistakes
- Mutating a field that feeds
__hash__or__eq__while the object is a dict key: the table stored it under the old hash, so lookups computed with the new hash take a different probe path and miss. - Reading "expected constant time" as a per-operation guarantee: a collision cluster, a resize, or a weak
__hash__can make one lookup cost many probes. - Relying on CPython's probe order or resize thresholds: both are implementation details that change between versions, unlike the language-level insertion-order guarantee.
- Defining
__eq__on a class meant to be a key but not__hash__: the class becomes unhashable, and if both are defined, equal objects with different hashes break the lookup invariant the table depends on.
Practice: Easy
- Run the worked example; add
print(len(mapping))and confirm the two colliding keys produced two entries. - Print
hash(a),hash(b), anda == b; label which call picks the slot and which confirms the candidate. - Insert a third key
Key("c", 1)with the same hash and print the dict; write down the key order and whether it matches insertion order.
Practice: Medium
- Write a
Keyvariant that returns0from__hash__for everything, build a dict of 100 such keys, count__eq__calls with a counter, and explain the cost of the collisions. - Build a dict of 1,000 string keys and a list of the same strings; run 1,000 membership tests against each and connect the result to the hashing path.
- Demonstrate the mutable-key failure: put a
Keyin a set, change itsvalue, and showkey in the_setisFalsewhile the object is still printed in the set.
Practice: Hard
- Implement a small open-addressing table for string keys with linear probing, insert, lookup, and delete with tombstones; explain each design decision against this lesson's concepts.
- Build a collision lab: force 50 keys to the same hash value, time insertion and lookup against 50 keys with distinct hashes, and explain the result with probe cost.
- Compare a set against a list for a membership-test workload in your own code; state which guarantees come from the language and which come from CPython's table implementation.
Lesson checklist
- I can trace a lookup through hash, probe, and equality for the worked example's two colliding keys.
- I can explain why equal objects must have equal hashes and what breaks when they do not.
- I can state what insertion order guarantees and what it does not, including the effect of delete-and-reinsert.
- I can diagnose a mutable-key failure and name one way to prevent it.
Remember
Dictionaries and sets are hash tables: `hash(key)` picks a starting slot, probing resolves collisions, and `==` confirms the candidate, which keeps lookups constant on average as the container grows. The structure's promises come with duties: keys must produce a stable hash that agrees with equality, and the performance guarantee is expected over many operations rather than exact for each one. Language-level behavior such as insertion order stands apart from CPython details such as probe sequences and resize thresholds.
Interview angles
What is the main purpose of **Hash tables**?+
A hash table uses a hash value to narrow the search for a key, then uses equality to confirm a match. Collisions are normal and handled by the table's probing strategy.
What should you pay attention to when using **Hashing**?+
Hashing turns a key into an integer that the table converts into a starting slot, using the key's __hash__. Equal objects must produce equal hashes, different keys may still collide, and a key's hash must stay stable while it is stored, or lookups will fail to find it.
How does **Collisions** fit into this lesson?+
Different keys can produce the same hash or probe position. A correct hash table resolves collisions and then uses equality to distinguish candidate keys.
Why does `key in some_set` return `False` after you mutate a field that `__hash__` depends on, even though the object is still in the set?+
The set stored the object under its hash at insertion time; the mutation changed the hash the object now produces, so membership testing probes a different slot and never compares against it. The object stays physically in the table but unreachable through lookup, which is why hash-relevant fields must stay stable while the object is stored.