Free lab Real Python 3. Zero installs. Your code stays in this browser. Open the playground

Dictionaries: Key → Value

15 min 30 XP
Study loop Read Predict Run Tweak Prove Review
Lesson 3 of 6 · View course roadmap
Step 1

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"] = 37 updates; new keys are added the same way
  • user.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] += 1 crashes on the first sighting. Use counts[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.

Step 2

Watch how it runs — line by line


        

Press play to watch Python execute this code, one line at a time.

Step 3

Try it yourself

Blank · autosaved

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

PYexample.py
+ Enter to run
Output appears here…
Step 4

Pass the challenge +30 XP

Blank · autosaved

Create a dict capitals mapping "France""Paris" and "Japan""Tokyo". Add "Italy""Rome", then print the capital of Japan and the number of entries.

Target output
Tokyo
3
PYchallenge.py
Run your code to check it…
Step 5

Check your understanding

1. What happens when you read a missing key with d["nope"]?
2. Which loops over both keys and values?
Last step

Your notes (saved on this device)

Tip: use and to move between lessons, K to search everything.

Your next ten minutes

Write Python that does something useful.

Start free. No install, no card, no passive video marathon.

Start learning free → Explore the path