Dictionary Methods

get, setdefault, items, pop and update - the methods that replace the if-key-in-dict dance.

Overview

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 — and there the KeyError is doing you a favour by failing loudly.

Do not reach for get reflexively. d.get(k) returning None where you expected a value produces a TypeError several lines later, far from the cause.

dict_methods.py

dict_methods.py Python 3
Output

                    

dict_patterns.py

dict_patterns.py Python 3
Output

                    

Worth knowing

d[k] raises on a missing key; d.get(k, default) does not.
d.items() yields key/value pairs; plain iteration gives keys only.
d.setdefault(k, []) returns the value, creating it first if the key was missing.
counts[w] = counts.get(w, 0) + 1 replaces the whole if/else counting block.

Dictionary Methods: A Practical Guide

A handful of dictionary methods replace the same few blocks of code people write by hand. Learning them is mostly learning to recognise the pattern they collapse.

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, which is easy to forget and produces 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

collapses to:

counts[w] = counts.get(w, 0) + 1

and, if counting is all you are doing, to Counter(words) from collections, which 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, and append to it" — three lines in one.

defaultdict(list) does the same job when every 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, which makes defaults | overrides a clean way to layer configuration.

Check yourself

0 of 3

Answer without scrolling back up.

  1. What does `d.get('missing')` return?

  2. `teams.setdefault(k, []).append(x)` does what?

  3. `for k in d` iterates over what?

Cheat sheet

Dictionary Methods

A handful of dictionary methods replace the same few blocks of code people write by hand. Learning them is mostly learning to recognise the pattern they collapse.

PYTHON · vizlearn.in/python/dictionary_methods.html

About the author

Ashish Jangra builds and maintains VizLearn. Every module here is written and the visualisation behind it hand-built, so the numbers in a readout come from the same code that draws the picture. Corrections are genuinely welcome and get priority over everything else — if a page states something wrong, or an animation misrepresents what the algorithm does, get in touch.