Dictionaries snippets
Small patterns for dictionaries that come up often in the exercises. Each one is short on purpose: the case it solves, the syntax, and the result.
Read a key with a fallback
Section titled “Read a key with a fallback”When a key might be missing and you want a default instead of a KeyError.
counts = {"a": 1}counts.get("a", 0) # → 1 key existscounts.get("z", 0) # → 0 key missing, returns the defaultget never raises, so it is the safe way to read a key you are not sure about.
Group items with defaultdict
Section titled “Group items with defaultdict”When you build lists (or counts) keyed by something, without checking whether the key exists first.
from collections import defaultdict
groups = defaultdict(list)for word in ["ant", "ape", "bee"]: groups[word[0]].append(word) # missing key auto-creates an empty list
dict(groups) # → {"a": ["ant", "ape"], "b": ["bee"]}defaultdict(list) creates an empty list the first time a key is touched, so the loop body stays one line. Convert back with dict(...) before returning, so callers get a plain dict.
Count occurrences with Counter
Section titled “Count occurrences with Counter”When you need how many times each item appears.
from collections import Counter
Counter("banana") # → Counter({"a": 3, "n": 2, "b": 1})Counter("banana").most_common(2) # → [("a", 3), ("n", 2)] top twoCounter is a dict subclass, so you can read it like a normal dict. Missing keys return 0 instead of raising.
Build a dict in one expression
Section titled “Build a dict in one expression”When you want a dict from an iterable, the same idea as a list comprehension.
nums = [1, 2, 3, 4]{x: x**2 for x in nums} # → {1: 1, 2: 4, 3: 9, 4: 16}
# swap keys and valuesd = {"a": 1, "b": 2}{v: k for k, v in d.items()} # → {1: "a", 2: "b"}Iterate over keys, values, or both
Section titled “Iterate over keys, values, or both”When you need to loop through a dict. items() gives you both at once.
prices = {"pen": 2, "book": 5}
for key in prices: # keys by default print(key) # pen / book
for name, price in prices.items(): print(name, price) # pen 2 / book 5Merge two dicts
Section titled “Merge two dicts”When you want to combine dicts. On a key clash the right-hand value wins.
a = {"x": 1, "y": 2}b = {"y": 9, "z": 3}a | b # → {"x": 1, "y": 9, "z": 3}The | merge operator was added in Python 3.9. On older versions use {**a, **b}, which does the same thing.