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)
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.