Skip to content

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.

When a key might be missing and you want a default instead of a KeyError.

counts = {"a": 1}
counts.get("a", 0) # → 1 key exists
counts.get("z", 0) # → 0 key missing, returns the default

get never raises, so it is the safe way to read a key you are not sure about.

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.

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 two

Counter is a dict subclass, so you can read it like a normal dict. Missing keys return 0 instead of raising.

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 values
d = {"a": 1, "b": 2}
{v: k for k, v in d.items()} # → {1: "a", 2: "b"}

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 5

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.