Dictionaries
A dictionary maps hashable keys to values and finds a key in roughly constant time, regardless of how many entries it holds. Since Python 3.7 it also preserves the order in which keys were first inserted.
Detailed Explanation
A dict answers one question extremely fast: "what value is stored under this key?" It does that with a hash table. When you write sessions[token] = user, Python calls hash(token), uses the low bits of that number as an index into an internal array, and stores the entry there. Looking the key up repeats the same arithmetic and jumps straight to the slot. No scanning. That is why membership on a dict is O(1) on average while membership on a list is O(n).
Two keys can hash to the same slot. That is a collision, and CPython resolves it with open addressing: it probes a deterministic sequence of other slots until it finds the key or an empty slot. Equality is what settles a match, so a key must support both __hash__ and __eq__, and objects that compare equal must hash equal. When the table gets about two-thirds full, CPython allocates a bigger one and reinserts everything. That resize is O(n), which is why insertion is amortised O(1) rather than strictly O(1).
Keys must be hashable, which in practice means immutable: strings, numbers, tuples of hashable things, frozensets. A list cannot be a key. If its contents changed, its hash would change and the entry would be stranded in the wrong slot, invisible to every future lookup.
Since CPython 3.6 a dict uses the "compact" layout: a small array of integer indices plus a dense array of (hash, key, value) entries appended in insertion order. Iteration walks the dense array, so you get insertion order for free, and the sparse part stores cheap integers rather than full pointers. This cut dict memory by roughly a fifth. Insertion order became a language guarantee in 3.7, not merely a CPython detail, so you may rely on it. Deleting a key leaves a tombstone in the dense array; heavy delete-and-reinsert cycles will eventually trigger a compacting resize.
| Operation | Average | Worst case | Why |
|---|---|---|---|
d[key], key in d | O(1) | O(n) | One hash and a short probe; worst case is every key colliding |
d[key] = value | O(1) amortised | O(n) | Occasional resize copies every entry |
del d[key], d.pop(key) | O(1) | O(n) | Same probe, then a tombstone |
len(d) | O(1) | O(1) | Count is stored |
iteration, d.items() | O(n) | O(n) | Walks the dense entry array |
value in d.values() | O(n) | O(n) | No index on values; linear scan |
dict(d), d.copy() | O(n) | O(n) | Copies every entry |
The worst case is real but rare. Because string hashing is randomised per process by default, an attacker cannot easily craft colliding keys from untrusted input; that randomisation was added precisely to stop hash-collision denial of service. Degenerate custom __hash__ methods, such as one that returns a constant, will reproduce O(n) behaviour on your own data.
Reach for a dict whenever you are keying data by identity: counting, grouping, caching, de-duplicating with extra payload, or representing a record with named fields. The cost is memory. A dict keeps spare slots and per-entry hashes, so a million-entry dict is much heavier than a million-element list.
Code Examples
# Counting word frequencies in a log file: the classic dict job.
lines = ["GET /home 200", "GET /home 200", "POST /login 401"]
status_counts = {}
for line in lines:
status = line.split()[-1]
# get() supplies a default instead of raising KeyError on the first sighting
status_counts[status] = status_counts.get(status, 0) + 1
print(status_counts) # {'200': 2, '401': 1}
# Keys keep their first-insertion order, guaranteed since Python 3.7.
print(list(status_counts)) # ['200', '401']
# Direct indexing raises; get() and setdefault() do not.
print(status_counts.get("500", 0)) # 0
status_counts.setdefault("500", 0) # inserts only if absent
print(status_counts) # {'200': 2, '401': 1, '500': 0}# Keys must be hashable. Immutable values qualify; lists do not.
distance = {("DEL", "BOM"): 1150} # tuple key: fine
try:
distance[["DEL", "BOM"]] = 1150 # list key: rejected
except TypeError as exc:
print(exc) # unhashable type: 'list'
# Views are live windows onto the dict, not snapshots.
inventory = {"bolts": 40, "nuts": 12}
low_stock = inventory.keys()
inventory["washers"] = 3
print(list(low_stock)) # ['bolts', 'nuts', 'washers'] <- view saw the insert
# Merging: | builds a new dict, |= updates in place (Python 3.9+).
defaults = {"retries": 3, "timeout": 10}
overrides = {"timeout": 30}
print(defaults | overrides) # {'retries': 3, 'timeout': 30} <- right side winsCommon Gotchas
Mutating a dict while iterating it raises
adding or deleting keys inside `for key in cache:` raises `RuntimeError: dictionary changed size during iteration`. Iterate over `list(cache)` when you intend to modify the dict in the loop.
Equal keys are the same key
`hash(1) == hash(1.0) == hash(True)`, and all three compare equal, so `{1: "a", 1.0: "b", True: "c"}` collapses to a single entry holding `"c"`. Mixed numeric key types quietly overwrite each other.
`in` checks keys, not values
`"admin" in roles` asks about keys. To search values you need `"admin" in roles.values()`, which is an O(n) scan with no index behind it.
Insertion order is not sort order
the 3.7 guarantee preserves the order keys were added, nothing more. Use `sorted(d.items())` or an explicit `key=` function when you need ordering by key or value.