Skip to content
Dictionary Techniques
step 1/7

Reading — step 1 of 7

Learn

~2 min readDictionaries and Sets

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()

python

get(key, 0) returns 0 for new words. Add 1 and store. Idiomatic and concise.

collections.Counter — counting made trivial

python

Counter is a dict subclass with extras: missing keys default to 0, and .most_common(n) returns the top-n entries.

Grouping with defaultdict

python

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

python

Works the same. setdefault(k, default) returns d[k] if it exists, otherwise inserts default and returns it.

Merging dictionaries

python

Later values win when keys collide.

Inverting a dict

python

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 over list(d) if you need to delete keys.
  • Using dict.fromkeys with 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 assignmentd.setdefault(), defaultdict, or Counter are usually cleaner.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…