Python’s dict is a mutable mapping that, since 3.7, preserves insertion
order. Its methods cover safe lookup, defaults, merging, removal, and the dynamic
view objects returned by keys, values, and items. This is a searchable
offline reference.
How it works
Each method lists its signature, return value, and behavior:
- Lookup —
get(key, default)returns a default instead of raising; indexingd[key]raisesKeyError. - Defaults —
setdefault(key, default)returns the value, inserting the default if the key is absent. - Merge —
update(other)writes another mapping’s pairs in; the|operator (3.9+) returns a merged dict. - Removal —
pop(key[, default])removes and returns a value;popitem()removes and returns the last inserted pair (LIFO since 3.7). - Views —
keys(),values(),items()return live views reflecting later changes; wrap inlist(...)for a snapshot.
Example
Group values into lists with setdefault:
groups = {}
for name, team in members:
groups.setdefault(team, []).append(name)
Common patterns and gotchas
Safe lookups without KeyError
The cleanest way to avoid a KeyError depends on whether you want to insert a default at the same time:
# Just look up, return None if missing — never inserts
value = d.get("key")
value = d.get("key", 0) # with a fallback value
# Look up AND insert if missing
count = d.setdefault("key", 0)
d["key"] += 1 # works reliably
The fromkeys trap
dict.fromkeys(keys, mutable_value) shares a single mutable object across all keys:
# Danger: all keys share one list
bad = dict.fromkeys(["a", "b", "c"], [])
bad["a"].append(1) # bad["b"] and bad["c"] also become [1]
# Fix: use a comprehension
good = {k: [] for k in ["a", "b", "c"]}
Merging dicts in different Python versions
# Python 3.9+ — creates a new merged dict
merged = first | second
# Python 3.9+ — update first in place
first |= second
# Python 3.5+ — spread syntax (use in dict literal)
merged = {**first, **second}
# All versions
first.update(second) # mutates first in place
View objects and iteration
keys(), values(), and items() return view objects that track the live dict state. They are safe to read and support in membership tests in O(1) for keys/items. The constraint is that you cannot modify the dict while iterating a view — doing so raises RuntimeError:
for key in list(d.keys()): # snapshot with list() if you need to delete during iteration
if should_remove(key):
del d[key]
Notes
- Insertion order is guaranteed since Python 3.7;
popitem()removes the last-inserted pair. - View objects are dynamic — they track changes to the dict. Iterating a view
while mutating the dict raises
RuntimeError. fromkeys(keys, value)is a classmethod; beware passing a mutable default — all keys share the same object.- This reference covers all standard
dictmethods.