Reading — step 1 of 7
Learn
Now that you know how to create, access, and modify dictionaries, it's time to learn the patterns professional Python developers use every day: counting, grouping, merging, inverting, and using collections.Counter and defaultdict for cleaner code.
Counting with .get()
get(key, 0) returns 0 for new words. Add 1 and store. Idiomatic and concise.
collections.Counter — counting made trivial
Counter is a dict subclass with extras: missing keys default to 0, and .most_common(n) returns the top-n entries.
Grouping with defaultdict
defaultdict(list) auto-creates an empty list the first time a new key is accessed — no more if key not in d: d[key] = [].
setdefault — the manual version
Works the same. setdefault(k, default) returns d[k] if it exists, otherwise inserts default and returns it.
Merging dictionaries
Later values win when keys collide.
Inverting a dict
Watch for collisions — if multiple keys map to the same value, only one survives. For one-to-many invert, use defaultdict(list).
Common mistakes
- Mutating a dict while iterating it raises
RuntimeError. Iterate overlist(d)if you need to delete keys. - Using
dict.fromkeyswith a mutable default:dict.fromkeys(["a", "b"], [])makes ALL keys share the SAME list. Mutating one mutates all. Use{k: [] for k in keys}instead. - Reaching for an
if key in d:check before assignment —d.setdefault(),defaultdict, orCounterare usually cleaner.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…