Code Reference

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

OperationExample
Create\{"a": 1\}, dict(a=1), dict([("a", 1)]), dict.fromkeys(keys, v=None)
Getd["a"] (KeyError), d.get("a", default)
Setd["a"] = 1, d.setdefault("a", 0)
Deletedel d["a"], d.pop("a", default), d.popitem() (LIFO 3.7+)
Cleard.clear()
Membershipk in d, k not in d (keys only)

Instance methods

MethodNotes
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+)

OpNotes
a | bNew dict; b wins on conflicts
a |= bIn-place update like update
\{**a, **b\}Unpack merge (literal)

Views — keys / values / items

ViewNotes
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 viewsReflect dict changes; do not mutate dict while iterating
Materializelist(d), list(d.items()) for a stable snapshot

Comprehension / related helpers

PatternNotes
\{k: v for k, v in pairs\}Dict comprehension
collections.CounterMultiset / counts
collections.defaultdictAuto-create missing values
collections.OrderedDictReorder 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] raises KeyError if missing—use .get or in.
  • Mutating a dict while iterating its views is unsafe; iterate over list(d) or copy.
  • Nested dicts share references—copy() is shallow; use copy.deepcopy when needed.
  • Using unhashable types as keys raises TypeError.
  • dict equality ignores order; do not rely on order for identity checks.

On this page