How does a Python dict work?
A hash table. The key's hash picks a slot, so a lookup computes an address rather than searching — which is why the size of the dictionary does not appear in the cost. Collisions are resolved by probing, and the table resizes and rehashes everything once it gets too full.
Overview
Computing an address instead of searching
Two steps: hash the key to a number, then fold that number into a slot index. The lookup goes straight to that slot and compares keys there. Neither step depends on how many entries the dictionary holds, which is the entire O(1) claim.
The comparison at the end is not optional. Two different keys can share a slot, so the answer is only correct because the key itself is checked — see hash tables for the machinery in full.
Step through it
What to watch
- The slot is computed, never searched for.
- A collision does not break anything — it costs an extra probe.
- A resize invalidates every slot, because the index is
hash % size.
Say this out loud
"Hash table. hash(key) picks a slot, so lookup is a computation, not a search - O(1) average. Collisions probe to another slot, and it resizes and rehashes when the load factor gets too high. Worst case is O(n) if everything collides."