Dictionaries: Key → Value
Lesson 3 of 6 · View course roadmap
Learn the idea
A dictionary maps keys to values — the single most important data structure in Python. Think of a real dictionary: look up a word (key), get a definition (value).
user = {"name": "Ada", "age": 36}user["name"]→"Ada";user["age"] = 37updates; new keys are added the same wayuser.get("email", "n/a")— safe lookup with a default (no crash if missing)"name" in user— check if a key exists
Loop over pairs with .items(): for key, value in user.items():. JSON — the language of web APIs — maps directly to Python dicts, which is why they matter so much.
Where you'll use this
Every JSON API payload, every database row, every config file becomes a dict in Python. Redis, MongoDB and Python's own objects (via __dict__) are key–value stores — this shape runs the internet.
Common mistakes
- KeyError from direct access on a maybe-missing key — use
.get(key, default)when absence is normal. - Using a list as a key → TypeError: keys must be hashable (str, int, tuple are fine).
- Counting without initialising:
counts[word] += 1crashes on the first sighting. Usecounts[word] = counts.get(word, 0) + 1— or Counter.
Pro tip
dict.setdefault(key, []).append(item) builds grouped data in one line, and {**defaults, **overrides} merges two dicts (right side wins). Both appear constantly in real code.
Watch how it runs — line by line
Press play to watch Python execute this code, one line at a time.
Try it yourself
The lesson example is loaded and ready — press Run, then change something and run it again. Breaking it is part of learning. Want a clean slate? Tap “New blank”.
Output appears here…
Pass the challenge +30 XP
Create a dict capitals mapping "France"→"Paris" and "Japan"→"Tokyo". Add "Italy"→"Rome", then print the capital of Japan and the number of entries.
Tokyo 3
print(capitals["Japan"]) then print(len(capitals)).
capitals = {"France": "Paris", "Japan": "Tokyo"}
capitals["Italy"] = "Rome"
print(capitals["Japan"])
print(len(capitals))
Run your code to check it…
Check your understanding
Your notes (saved on this device)
Tip: use ← and → to move between lessons, ⌘K to search everything.