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_patterns.py
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.