Skip to content
Lesson 5 of 12

Step 1 of 7 · Reading · ~2 min

Learn

Dictionaries 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.

Python 3.9 added a | b as a dict-merge operator, and you will meet it in modern code. The grader that runs your exercises is Python 3.8, where it is not a merge at all — {"x": 1} | {"y": 2} raises TypeError: unsupported operand type(s) for |: 'dict' and 'dict'. Use {**a, **b} in anything you submit here.

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.
Up nextSets and OperationsDictionaries and Sets

Discussion

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

Sign in to post a comment or reply.

Loading…