Dict lookup: hash table with open addressing and compact storage
A dict is a hash table. On lookup, CPython computes hash(key), masks it to an index into a sparse indices array, and compares the key in the corresponding entry. If the slot is empty, lookup fails; if occupied, it compares hashes and then equality. Collisions are resolved with open addressing and a perturb-based probe sequence, not separate chaining. Modern CPython also uses a compact layout: a dense entries array stores keys and values in insertion order, and a sparse indices array maps hash slots to entry positions. This improves memory locality and preserves insertion order.
Average O(1) assumes a good hash function, low collision rate, and bounded load factor; CPython resizes when the table becomes too full.
Worst-case lookup is O(n) if many keys collide or if an attacker can force collisions.
Trade-off: custom objects need consistent hash and eq. If two objects are equal they must have the same hash; otherwise dict/set lookups break.
Common mistake: assuming dict lookup is always O(1) or that mutable keys are allowed. Keys must be hashable, and mutating a key after insertion corrupts lookup.
Version note: the compact dict layout landed in CPython 3.6 and insertion order became a language guarantee in 3.7. Hash randomization is enabled by default in modern Python for security.
0-2 years experience
2-5 years experience
5-8 years experience
8+ years experience