get, instead of checking first
prices["kiwi"] # KeyError
prices.get("kiwi") # None
prices.get("kiwi", 0) # 0
get is for when a missing key is expected and has a sensible default. Square brackets are for when a missing key is a bug. The KeyError is doing you a favor by failing loudly.
Do not reach for get reflexively. d.get(k) returning None when you expected a value makes a TypeError surface a few lines later, far from the actual cause.
Dictionaries are one of the most heavily used data structures in Python. They appear in configuration, in function keyword arguments, in JSON responses from web APIs, and as the backing store for object attributes. Knowing the methods well saves you from writing loops that the methods already handle.
The .items() method returns every key-value pair as a sequence of tuples. It is how you loop over both keys and values at the same time: for k, v in d.items():. Before Python 3, this returned a list. Now it returns a view, a lightweight object that reflects the dictionary without copying it.
.keys() and .values() return views of just the keys or just the values. You rarely call .keys() explicitly because looping over a dictionary directly gives the keys: for k in d: is the same as for k in d.keys():.
.update() merges another dictionary into the current one. Existing keys get overwritten. d.update(other) is the in-place version of {**d, **other}, which creates a new dictionary with all entries from both.
.pop(key) removes a key and returns its value. It raises KeyError if the key is missing, unless you give a default: .pop(key, None). .setdefault(key, value) returns the existing value for a key if it exists, or inserts the default and returns it if the key is missing.
This page covers get, items, keys, values, update, pop, setdefault, and the patterns they replace.
items, keys, values
for k, v in d.items():
items() is what you want most of the time. Plain for k in d iterates keys. This Is easy to forget and makes a confusing error when you then treat k as a value.
All three are views, not lists: they reflect later changes to the dict and are cheap to create. Wrap in list() if you need a snapshot. And you do need one if you intend to modify the dict while looping.
The counting pattern
The block everyone writes first:
if w in counts:
counts[w] += 1
else:
counts[w] = 1
merges to:
counts[w] = counts.get(w, 0) + 1
and, if counting is all you're doing, to Counter(words) from collections. This Is faster and says what it means.
The grouping pattern
teams.setdefault(team, []).append(name)
setdefault returns the value at that key, inserting the default first if the key was absent. So this reads "get the list for this team, making an empty one if needed. Append to it". Three lines in one.
defaultdict(list) does the same job when each access should create a default. setdefault is better when only some do.
pop and update
d.pop("a") # remove and return; raises if absent
d.pop("a", None) # ...unless given a default
d.update(other) # merge in place
a | b # a new merged dict (3.9+)
With |, the right-hand side wins on conflicts. This Makes defaults | overrides a clean way to layer configuration.
Views, and why they are not lists
keys(), values() and items() return views: live windows onto the dict rather than snapshots of it. Add a key and each existing view reflects it right away, because a view holds no data of its own.
That is fast and it has one consequence worth knowing. Modifying a dict while looping over one of its views raises RuntimeError: dict changed size during iteration. The fix is to iterate over a snapshot:
for key in list(d):
if should_remove(key):
del d[key]
list(d) copies the keys first. So The loop is walking its own list and the dict is free to change underneath.
Key and item views also behave like sets. This Is at times very handy: d1.keys() & d2.keys() gives the keys both dicts share, without a loop.
Order is guaranteed now
Since Python 3.7, dicts keep insertion order as a language ensure rather than an setup accident. That is why dict.fromkeys(items) is the standard order-preserving deduplication, and why iterating a dict makes a stable, predictable sequence.
It doesn't make a dict a substitute for a sorted structure - the order is insertion order, not sorted order - but it does mean you can lean on what you put in first coming out first.
Choosing between get, setdefault and defaultdict
Three tools that share, and the gap is about what should happen when a key is missing.
get reads and never writes. Use it when a missing key has a sensible fallback and you don't want to add any of it to the dict.
setdefault reads and writes: it inserts the default when the key is absent and returns what is now there. Use it for the grouping idiom. Here You want the list to exist so you can append to it.
defaultdict(list) moves that action into the dict itself, so each missing key springs into existence on access. Use it when *each* access should create a default. Its downside is just that: a typo'd key lookup silently creates an empty entry instead of raising. This Can mask a bug.
Merging
merged = {**defaults, **overrides} # 3.5+
merged = defaults | overrides # 3.9+
defaults |= overrides # in place
Later keys win in all three. This is the clean way to layer configuration, and it beats a loop of if key not in d rules because the precedence is stated by the order of the operands rather than buried in the logic.
Counter, and the four things it gives you
Counting is common enough that the standard library has a dict subclass for it, and knowing four of its actions drops a lot of hand-written code:
from collections import Counter
text = "the cat and the hat and the bat"
counts = Counter(text.split())
print(counts.most_common(2))
print(counts["the"], counts["dog"])
print(sum(counts.values()))
[('the', 3), ('and', 2)]
3 0
8
First, it counts any of it iterable in one call. So The loop disappears. Second, most_common(n) sorts by count and gives the top n. This Is the question people really want answered and is or else a sorted with a key. Third, a missing key returns 0 rather than raising — and, unlike defaultdict, it doesn't insert the key on access. So Reading doesn't quietly grow the dict. Fourth, counters support math: a + b merges counts and a - b subtracts them. This Is a neat way to diff two collections.
It's still a dict, so all else on this page applies to it.
What can be a key, and why
Any object can be a key if it's hashable. This means immutable all the way down. Strings, numbers, booleans and tuples of those are fine. Lists, dicts and sets aren't, and a tuple holding a list isn't either, because hashing it has to hash its contents.
The reason is how a dict works. It finds a hash of the key, uses that to decide where to store the entry. Looks in the same place later. If a key could change after insertion, its hash would change, and the entry would be sitting a place the lookup will never search. Rather than allow that, Python refuses to hash mutable types at all.
Two consequences are worth knowing. 1, 1.0 and True all hash the same and compare equal, so they're the *same key*. {1: "a", True: "b"} has one entry. And a tuple key is the standard way to index by more than one thing: grid[(row, col)] is a just right plain dict lookup, and the brackets around the tuple are optional.
Custom classes are hashable by default, using identity, which means two distinct instances with the same contents are different keys. If you want them to be the same key, define __eq__ and __hash__ together — or use a frozen dataclass, which writes both for you.
A dictionary instead of a chain of elif
Once functions can be values, a dict replaces a whole shape of code:
def add(a, b): return a + b
def sub(a, b): return a - b
OPS = {"+": add, "-": sub}
print(OPS["+"](3, 4))
print(OPS.get("*", lambda a, b: None)(3, 4))
7
None
Checked with an if/elif chain, this separates the table of options from the code that uses it. Adding an op is one dict entry rather than another branch, the set of valid options can be listed with OPS.keys(), and the same table can drive a help message or validate input.
The pattern generalises well beyond math: handlers keyed by message type, formatters keyed by file extension, validators keyed by field name. It's the same idea as the menu earlier in the track, and it's worth reaching for when a chain of elif is checking one value against a list of constants.
Where an if chain is still better: when the rules aren't simple equality — ranges, combinations, any of it needing and — a dict can't express the question, and forcing it to is worse than the chain.
Getting the items out in a useful order
A dict keeps insertion order. This Is rarely the order you want to report in. sorted takes the same key arg here as all over else, and d.items() gives it pairs to work with.
Sorting by key is sorted(d.items()). This Works because tuples compare element by element and the key is first. Sorting by value needs a key function that reaches for the second element — key=lambda kv: kv[1], or key=itemgetter(1) — and adding reverse=True gives you largest first. For a top-n rather than a full sort, heapq.nlargest(3, d.items(), key=...) does less work, and Counter.most_common(3) does it for you when the values are counts.
The result is a list of tuples, not a dict. If you need a dict back in that order, wrap it: dict(sorted(d.items())) builds a new one, and since 3.7 the insertion order it gets is the sorted order you just made. This is the standard way to give a "sorted dict" in Python, and it's worth knowing that it's a snapshot. Later insertions go on the end, not into their sorted spot.
One detail that bites when sorting by value: ties come out in what order they were already in, because sorted is stable. That is often what you want, and when it isn't, the fix is a tuple key that names the tiebreak by name, such as key=lambda kv: (-kv[1], kv[0]) for "highest count first, then alphabetical".
Comprehensions over dictionaries
The methods on this page and dict comprehensions cover the same ground from two directions, and knowing which reads better saves a lot of loops.
A comprehension is the right tool when you're building a new dict from an old one: filtering out entries below a threshold, transforming each value, swapping keys and values, or building a lookup table from a list of records. {k: v for k, v in d.items() if v > 0} is one line, and the option is three lines with an accumulator.
The methods are the right tool when you're updating a dict in place, or when the op has a name — update, setdefault, pop. Rebuilding a whole dict with a comprehension to change one entry is wasteful and reads as though a thing more complicated is happening.
The case where people reach for the wrong one is counting and grouping. A comprehension can't build up, because each iteration makes an free entry with no access to what came before. That is just why Counter, setdefault and defaultdict exist, and why a grouping loop stays a loop.
Questions people ask about Dictionary Methods
Is d.get(k) the same as d[k] with a try? In effect yes, and get is clearer. Use brackets when a missing key means a bug.
Why did my loop raise "dict changed size during iteration"? Because you added or removed a key while iterating a live view. Iterate list(d) instead.
What is the difference between update and |? update modifies in place and returns None. | returns a new dict and leaves both operands alone.
Are dicts sorted? No. They keep insertion order, which isn't the same thing. sorted(d.items()) when you want sorted.
How do I invert a dict? {v: k for k, v in d.items()}, remembering that duplicate values collapse — the last one wins.
Is defaultdict always better than setdefault? No. defaultdict creates an entry on any missing lookup, including a typo, which can hide bugs. Use it when each access should create a default.
How do I get the first key? next(iter(d)). There's no indexing, because a dict isn't a sequence.
Can I use + to merge two dicts? No. Use | on 3.9 and later, {**a, **b} before that, or update for in-place.
Does pop work without a key? popitem() drops and returns the last inserted pair. This Is handy for draining a dict in a loop.
How do I count without importing Counter? d[k] = d.get(k, 0) + 1 in a loop. Counter is faster and clearer, but the one-liner is worth knowing for when the import isn't worth it.
What happens if I use an unhashable key by mistake? You get TypeError: unhashable type: 'list' at the moment of insertion, which names the type and is one of the clearer error messages in the language.
Is there a frozen dict? Not in the standard library. types.MappingProxyType(d) gives a read-only view of one. This Covers most of the reasons people want it.
Dictionary Methods: recap in one screen
get reads with a fallback, setdefault reads and inserts, defaultdict inserts on each miss — pick by what should happen to the dict.items() is the loop you often want. keys(), values() and items() are live views, not snapshots.- Iterate
list(d) when the loop body might change the dict. - Keys must be hashable. This Means immutable all the way down. Tuples are the standard multi-part key.
- A dict of functions replaces a chain of
elif that is testing one value against constants.