Intermediatecomparison
What is the time complexity of a dictionary lookup, and why does it matter?
Source: Python tutorial: data structures
Quick answer
O(1) on average: the key is hashed to find its slot directly. A list membership test is O(n), scanning item by item. In pipelines this decides whether matching a million records against a lookup takes milliseconds or hours: build a dict or set once, then look up.
O(1) on average: the key is hashed to find its slot directly. A list membership test is O(n), scanning item by item. In pipelines this decides whether matching a million records against a lookup takes milliseconds or hours: build a dict or set once, then look up. Keys must be hashable (immutable types like str, int, tuple).
Animated explanation
dict / set lookup
- Hash to the slot
- O(1) on average
- Build once, look up many times
list membership
- Scan item by item
- O(n)
- A million lookups take far longer
Key points
- hashing
- O(1) vs O(n)
- build lookup once
- hashable keys