Dictionaries
Python · Reference cheat sheet
Dictionaries
Python · Reference cheat sheet
📋 Overview
A dict maps hashable keys to values. Insertion order is preserved (3.7+). Use for lookups, configs, JSON-like data, and counting. Prefer dict / collections.Counter / defaultdict over ad-hoc nested structures when possible.
🔧 Core concepts
Create / access / mutate
| Operation | Example |
|---|---|
| Create | \{"a": 1\}, dict(a=1), dict([("a", 1)]), dict.fromkeys(keys, v=None) |
| Get | d["a"] (KeyError), d.get("a", default) |
| Set | d["a"] = 1, d.setdefault("a", 0) |
| Delete | del d["a"], d.pop("a", default), d.popitem() (LIFO 3.7+) |
| Clear | d.clear() |
| Membership | k in d, k not in d (keys only) |
Instance methods
| Method | Notes |
|---|---|
get(k[, default]) | Return value or default (None) |
setdefault(k[, default]) | Get or insert default; return value |
update([other], **kw) | Merge mappings/pairs in place |
pop(k[, default]) | Remove key; return value (or default / KeyError) |
popitem() | Remove and return (k, v) last inserted |
clear() | Remove all items |
copy() | Shallow copy |
fromkeys(iterable, value=None) | Classmethod: new dict with shared default |
Merge operators (3.9+)
| Op | Notes |
|---|---|
a | b | New dict; b wins on conflicts |
a |= b | In-place update like update |
\{**a, **b\} | Unpack merge (literal) |
Views — keys / values / items
| View | Notes |
|---|---|
d.keys() | Dynamic set-like view of keys |
d.values() | Dynamic view of values |
d.items() | Dynamic set-like view of (k, v) |
| Set ops on keys/items | &, |, -, ^ with other views/sets |
| Live views | Reflect dict changes; do not mutate dict while iterating |
| Materialize | list(d), list(d.items()) for a stable snapshot |
Comprehension / related helpers
| Pattern | Notes |
|---|---|
\{k: v for k, v in pairs\} | Dict comprehension |
collections.Counter | Multiset / counts |
collections.defaultdict | Auto-create missing values |
collections.OrderedDict | Reorder helpers; plain dict keeps insert order |
Keys must be hashable (str, int, tuple of hashables—not list/dict).
💡 Examples
Safe access and merge:
user = {"id": 1, "name": "Ada"}
role = {"role": "admin"}
print(user.get("email", "n/a"))
merged = user | role # {"id": 1, "name": "Ada", "role": "admin"}Counting and grouping:
from collections import Counter, defaultdict
words = ["a", "b", "a", "c", "b", "a"]
print(Counter(words)) # Counter({'a': 3, 'b': 2, 'c': 1})
by_len: dict[int, list[str]] = defaultdict(list)
for w in words:
by_len[len(w)].append(w)Dict comprehension / invert:
scores = {"alice": 10, "bob": 7}
passed = {k: v for k, v in scores.items() if v >= 8}
# invert (values must be unique/hashable)
inv = {v: k for k, v in scores.items()}Pattern matching (3.10+):
payload = {"type": "user", "id": 42}
match payload:
case {"type": "user", "id": int(uid)}:
print("user", uid)
case _:
print("unknown")⚠️ Pitfalls
d[key]raisesKeyErrorif missing—use.getorin.- Mutating a dict while iterating its views is unsafe; iterate over
list(d)or copy. - Nested dicts share references—
copy()is shallow; usecopy.deepcopywhen needed. - Using unhashable types as keys raises
TypeError. dictequality ignores order; do not rely on order for identity checks.