Python Dicts

get/set, defaultdict, comprehensions, and merging

40 min · interactive lesson with runnable code and 8 graded exercises.

What you'll be able to do

  • Read and write keys safely — [] vs .get()
  • Explain why dict lookup is O(1) on average
  • Count and group with defaultdict
  • Merge dicts with update, {a, b}, | and |=

What is a dict?

Key → value maps

A dict maps keys to values. If lists are sequences, dicts are lookup tables. Since Python 3.7 they keep insertion order.

  • keys must be hashable
  • values can be anything
  • ordered by insertion (3.7+)
  • mutable
  • get / set / in are O(1) on average

Ways to create one:

Why lookup is O(1)

Hash tables under the hood

A dict doesn't search for your key. It hashes the key into a number, uses that to pick a slot, and jumps straight there. Insert and look up keys below — compare the slots checked with how many items a plain list would scan:

Get, set, and methods

[] vs .get()

Missing-key patterns

get, setdefault, defaultdict

Counting and grouping are where missing keys show up constantly. Three ways to handle them — all produce the same result:

Dict comprehensions

Build and transform maps

Merging dicts

update, **, |, |=

Four ways to merge. When both dicts have a key, the right-hand dict wins:

Nested dicts & valid keys

Configs, JSON, hashability

Keys must be hashable — roughly, immutable all the way down. Sort these:

Common pitfalls

Spot the bug