Dictionaries
Key-value lookups, safe access, merging, looping, dict comprehensions, nested data, Counter and defaultdict.
A dictionary (dict) maps keys to values, like a real dictionary maps words to definitions. Instead of asking "what's at position 3?", you ask "what's the price of mango?" or "what's this user's email?". Dicts are fast, flexible and everywhere: JSON from web APIs, configuration files, database rows, caches and counting.
Creating dictionaries#
Keys must be hashable — strings, numbers, tuples — and each key appears only once. Values can be anything, including lists and other dicts.
Reading values safely#
Square brackets raise KeyError when the key is missing. get() returns None or a default instead:
Use [] when a missing key is a bug that should fail loudly; use get() when a missing key is normal.
Adding, updating and removing#
The merge operators (Python 3.9+) combine dicts; values from the right-hand side win:
Looping over dictionaries#
Dictionaries remember insertion order (guaranteed since Python 3.7) — they don't sort themselves. min(prices, key=prices.get) is a neat idiom: it compares keys by their values.
Don't add or remove keys while iterating over a dict — Python raises RuntimeError. Loop over list(d) if you must.
Dictionary comprehensions#
Build dicts in one expression, just like list comprehensions:
Nested data#
Real data — especially JSON from APIs — is dicts inside lists inside dicts:
The chained .get(..., {}) pattern safely digs into optional nested keys.
Counting and grouping#
Two jobs come up constantly: counting things and grouping things. You can do them with plain dicts:
But the collections module has purpose-built tools:
Dict views#
keys(), values() and items() return live views, not copies — they reflect later changes. Key views even support set operations:
Worked example: a word-frequency report#
Common mistakes#
KeyErroron missing keys — useget(),in, orsetdefault/defaultdict.- Using a list as a key — convert it to a tuple.
- Expecting dicts to be sorted — they keep insertion order; sort explicitly with
sorted(d.items()). - Mutating a dict while looping over it — iterate over
list(d.items())instead. for k in d.keys()— just writefor k in d.
What's next#
With lists, tuples, sets and dicts, you have Python's full toolkit of built-in data structures. Next we'll organise code itself into reusable pieces with functions.
Check your understanding
Quick quiz
1.What does
user.get("email", "n/a")return ifuserhas no"email"key?2.Since Python 3.7, what order do you get when iterating over a dict?
3.Which is the most Pythonic way to count word occurrences in a list
words?
Finished reading?
Mark this lesson complete to track your progress.