🗂️ Python data structures · session 2 of 12 · 60 minutes · free
All about dictionaries
A list finds things by position; a dictionary finds them by name. Beatbox's library needs that: type a song's title and get its plays, its artist, its tags, instantly. Today you build it with keys and values, loop through it, count with it and nest records inside it.

A complete lesson · 60 minutes
Teach it, see it, practise it, all on this page.
Open this page with your learner and work down it, or press Teach this lesson to go through it one step at a time on a big screen. Every section has something to do.
- Warm-up3 min
- Warm-up games5 min
- Dictionaries: keys and values9 min
- Looping and dictionary methods9 min
- Counting, nested dictionaries and comprehensions9 min
- Beatbox play counter7 min
- Song lookup service7 min
- Class report card5 min
- Quiz5 min
- Set the after-class project1 min
By the end you can
- Make a dictionary and read, add and change values by key
- Use in and get() so a missing key never crashes the program
- Loop over keys, values and items(), and use del, pop, update and sorted()
- Count things with a dictionary, store records in nested dictionaries, and write a dict comprehension
Before you start
- Lists, indexes and for loops (lesson 1)
- Writing functions with def and return
- f-strings
Have ready
- This page (the code runs in the browser)
- Paper to draw a key → value table
Grades 9 to 12 · ages 14 to 18 · after a first Python course
Warm-up · think first
Your contacts app has 500 people. You type 'Maya' and her number appears instantly. How do you think the app finds it so fast?
Show the answer
It doesn't scan all 500 in order. It looks the name up directly, like a word in a printed dictionary. Python's dictionary works the same way: the name is the key, the number is the value.
Teacher tip: Ask what else they look up by name rather than by position.
🎮 Warm-up games · 5 quick games
Play with Bolt the robot
Five minutes in the Beatbox studio. Vote, say why, then show the answer.
- Which one could NOT be a dictionary key? ("Glow" · 42 · (1, 2) · [1, 2])
Answer: [1, 2] is the odd one out: keys must never change, and a list can change. Strings, numbers and tuples can be keys. - A dictionary can hold two items with the same key. (Always · Sometimes · Never)
Answer: Never — Never. Each key appears once; setting it again replaces the old value. - In a phone's contacts, which part is the key and which part is the value?
Answer: The name is the key; the number (or a whole record: number, email, photo) is the value. You look up by name. - Would you rather find a song's plays in a list of 2,000 pairs, or in a dictionary? (A list of 2,000 pairs · A dictionary)
Answer: The dictionary: plays["Glow"] jumps straight to the answer without searching the list. - Name three dictionaries hiding in apps you use.
Answer: Usernames to profiles, product codes to prices, words to translations, songs to play counts: all key → value.
Three levels, like a real engineer
Use it. Tweak it. Build it.
First use what the lesson shows exactly as it is, then change one key thing and see what happens, then make your own.
- 🔒
Level 1 · Use it
Run Pet Counter
Run this exact code: pets = {'dog': 4, 'cat': 3}; print(pets['dog']); print('bird' in pets); print(pets.get('bird', 0)). Notice which lines print and why.
- 🔧
Level 2 · Tweak it
Tweak Pet Values
In that pet code, change 'cat' to 'lion' and 0 to 99 in get('bird', 0). Predict what print(pets.get('bird', 99)) and print('lion' in pets) will show. Run it.
- 🛠️
Level 3 · Build it
Build Your Own Dict
Make your own dictionary for 3 friends and their ages. Add one new friend, change one age, use get() for a missing friend, then loop over items() and print each pair. Test it.
🗺️ Play the Lesson QuestThree worlds, one for each level, with short stages that bring back what you miss.
Part 1 of 3 · learn, see, practise
Dictionaries: keys and values
Beatbox dev log, day 3. Users search by title, not by position. A dictionary stores each song's title as a key and its play count as the value, so plays["Glow"] answers instantly.
A dictionary stores pairs: each key points to a value. It is written in curly brackets with a colon in each pair: plays = {"Glow": 3, "Rush": 5}.
Read a value with its key in square brackets: plays["Rush"] is 5. The same syntax adds a new pair or changes an old one: plays["Echo"] = 8 adds, plays["Glow"] += 1 changes.
Keys are unique and must be unchangeable values such as strings, numbers or tuples. Values can be anything: numbers, strings, lists, even other dictionaries.
Asking for a key that is not there, plays["Nova"], stops the program with KeyError. Check first with "Nova" in plays, or use plays.get("Nova", 0), which gives 0 instead of an error.
- d[key] reads, d[key] = value adds or changes.
- Missing keys: use in to check, or get(key, default).
in checks the keys, not the values: 5 in plays is False even though 5 is one of the values.
len(plays) counts the pairs. An empty dictionary is {}.
🧑🏫 Teacher: type this live with the class
Build the play counter
plays = {"Glow": 3, "Rush": 5}Curly brackets; each pair is key: value.
print(plays["Rush"])Look up by key, not by position: 5.
plays["Echo"] = 8A new key adds a pair.
plays["Glow"] += 1An existing key changes its value: Glow is now 4.
print(plays)Run it: {'Glow': 4, 'Rush': 5, 'Echo': 8}.
print(len(plays), "Nova" in plays)3 pairs; in checks the keys: False.
print(plays.get("Nova", 0))get gives a default instead of an error: 0.
▶ Output
(nothing is printed)
📦 Memory boxes
▶ Output
Songs: 2
Glow is by Ana
{'Glow': 'Ana', 'Rush': 'Bea', 'Echo': 'Cy'}
Nova is not in the library
unknown artist📦 Memory boxes
{'Glow': 'Ana', 'Rush': 'Bea', 'Echo': 'Cy'}dictsong'Nova'strTry print(library["Nova"]) and read the KeyError. Then fix it with get or with an if ... in check.
Puzzle break: keys and values
Read it the way Python does, line by line, before anyone runs it.
- Puzzle 1: say what happens before you run it
- Puzzle 2: say what happens before you run it
- Puzzle 3: fill the gap
Practise it
Start with the warm-up and go as far as you can. The stretch questions are meant to be hard.
1.1 Make a dictionary called plays with "Glow": 3 and "Rush": 5, then print it.
▶ Output
(nothing is printed)
📦 Memory boxes
🧑🏫 Model answer (for the teacher)
Teacher eyes only: hide the answers before you share your screen.
The answer green = the 2 lines the student writes
plays = {"Glow": 3, "Rush": 5}print(plays)
What it prints
{'Glow': 3, 'Rush': 5}
What ✓ Check looks for
- it prints exactly:
{'Glow': 3, 'Rush': 5} - In the code: Use curly brackets: plays = {...}.
1.2 Print how many plays "Echo" has, using its key.
▶ Output
(nothing is printed)
📦 Memory boxes
{'Glow': 3, 'Rush': 5, 'Echo': 8}dict🧑🏫 Model answer (for the teacher)
Teacher eyes only: hide the answers before you share your screen.
The answer green = the 1 line the student writes
plays = {"Glow": 3, "Rush": 5, "Echo": 8}print(plays["Echo"])
What it prints
8
What ✓ Check looks for
- it prints exactly:
8
- In the code: Use plays["Echo"].
1.3 Add "Drift" with 0 plays, add 1 to "Glow", then print the dictionary.
▶ Output
(nothing is printed)
📦 Memory boxes
{'Glow': 3, 'Rush': 5}dict🧑🏫 Model answer (for the teacher)
Teacher eyes only: hide the answers before you share your screen.
The answer green = the 3 lines the student writes
plays = {"Glow": 3, "Rush": 5}plays["Drift"] = 0plays["Glow"] += 1print(plays)
What it prints
{'Glow': 4, 'Rush': 5, 'Drift': 0}
What ✓ Check looks for
- it prints exactly:
{'Glow': 4, 'Rush': 5, 'Drift': 0} - In the code: Add a key with plays["Drift"] = 0.
1.4 Print the plays for "Nova" using get with 0 for a missing song, then the same for "Rush".
▶ Output
(nothing is printed)
📦 Memory boxes
{'Glow': 3, 'Rush': 5}dict🧑🏫 Model answer (for the teacher)
Teacher eyes only: hide the answers before you share your screen.
The answer green = the 2 lines the student writes
plays = {"Glow": 3, "Rush": 5}print(plays.get("Nova", 0))print(plays.get("Rush", 0))
What it prints
0 5
What ✓ Check looks for
- it prints exactly:
0 5
- In the code: Use plays.get("Nova", 0).
1.5 Write plays_of(song) that returns the song's plays, or -1 when it is not in the dictionary (check with in). Print plays_of("Rush") and plays_of("Nova").
▶ Output
(nothing is printed)
📦 Memory boxes
{'Glow': 3, 'Rush': 5}dict🧑🏫 Model answer (for the teacher)
Teacher eyes only: hide the answers before you share your screen.
The answer green = the 6 lines the student writes
plays = {"Glow": 3, "Rush": 5} def plays_of(song): if song in plays: return plays[song] return -1 print(plays_of("Rush"))print(plays_of("Nova"))
What it prints
5 -1
What ✓ Check looks for
- it prints exactly:
5 -1
- With
plays = {"Nova": 2}, it prints exactly:-1 2
- In the code: Check with if song in plays:
1.6 Swap keys and values: build a new dictionary that maps each number to its song, then print it.
▶ Output
(nothing is printed)
📦 Memory boxes
{'Glow': 1, 'Rush': 2, 'Echo': 3}dict🧑🏫 Model answer (for the teacher)
Teacher eyes only: hide the answers before you share your screen.
The answer green = the 4 lines the student writes
codes = {"Glow": 1, "Rush": 2, "Echo": 3}swapped = {}for song, n in codes.items(): swapped[n] = songprint(swapped)
What it prints
{1: 'Glow', 2: 'Rush', 3: 'Echo'}
What ✓ Check looks for
- it prints exactly:
{1: 'Glow', 2: 'Rush', 3: 'Echo'} - With
codes = {"a": 9}, it prints exactly:{9: 'a'} - In the code: Loop over the pairs.
Part 2 of 3 · learn, see, practise
Looping and dictionary methods
The weekly report needs every song and its plays, the total, the most played, songs in A to Z order, and old songs removed. Loops and a handful of methods do it all.
for song in plays: loops over the keys. plays.values() gives the values, and plays.items() gives (key, value) pairs, so for song, n in plays.items(): reads both at once.
del plays["Rush"] removes a pair; plays.pop("Glow") removes it and gives back its value; plays.update(other) adds or overwrites the pairs from another dictionary.
sorted(plays) gives the keys in order, and sum(plays.values()) adds the values. max(plays, key=plays.get) finds the key with the biggest value.
A dictionary remembers the order the keys were added. Changing a value keeps its place; a new key goes to the end.
- for k, v in d.items(): reads keys and values together.
- del removes; pop removes and returns; update merges.
Never add or delete keys while looping over the same dictionary: loop over list(d) instead.
A quick text bar chart: print(song, "#" * n) draws n hashes for each song.
🧑🏫 Teacher: type this live with the class
The weekly report
chart = {"Glow": 4, "Rush": 5, "Echo": 8}Three songs and their plays.
for song in chart:Looping over a dictionary visits its keys.
print(song, chart[song])Use the key to get each value.
for song, n in chart.items():items() gives each key and value together.
print(song, "#" * n)A tiny bar chart: one # per play.
del chart["Rush"]del removes a key and its value.
print(sorted(chart), sum(chart.values()))Keys in A to Z order, and the total of the values.
▶ Output
(nothing is printed)
📦 Memory boxes
▶ Output
Glow: ############ 12
Rush: ####### 7
Echo: ############### 15
Drift: ######### 9
Total plays: 43
Most played: Echo
Drift Echo Glow Rush
{'Glow': 12, 'Rush': 8, 'Echo': 15, 'Drift': 9, 'Nova': 3}📦 Memory boxes
{'Glow': 12, 'Rush': 8, 'Echo': 15, 'Drift': 9, 'Nova': 3}dicttotal43intsong'Rush'strn9intChange a number in plays and run it again: the bar chart and the total follow. Then try sorted(plays, key=plays.get, reverse=True).
Puzzle break: loops and methods
Read it the way Python does, line by line, before anyone runs it.
- Puzzle 1: say what happens before you run it
- Puzzle 2: find the bug
- Puzzle 3: say what happens before you run it
Practise it
Start with the warm-up and go as far as you can. The stretch questions are meant to be hard.
2.1 Print every song and its plays on its own line, like Glow 3, using items().
▶ Output
(nothing is printed)
📦 Memory boxes
{'Glow': 3, 'Rush': 5}dict🧑🏫 Model answer (for the teacher)
Teacher eyes only: hide the answers before you share your screen.
The answer green = the 2 lines the student writes
plays = {"Glow": 3, "Rush": 5}for song, n in plays.items(): print(song, n)
What it prints
Glow 3 Rush 5
What ✓ Check looks for
- it prints exactly:
Glow 3 Rush 5
- In the code: Loop with for song, n in plays.items():
2.2 Print the total number of plays, using values().
▶ Output
(nothing is printed)
📦 Memory boxes
{'Glow': 3, 'Rush': 5}dict🧑🏫 Model answer (for the teacher)
Teacher eyes only: hide the answers before you share your screen.
The answer green = the 1 line the student writes
plays = {"Glow": 3, "Rush": 5}print(sum(plays.values()))
What it prints
8
What ✓ Check looks for
- it prints exactly:
8
- In the code: Use plays.values().
2.3 Remove "Rush" with del and print the dictionary, then remove "Glow" with pop and print the plays it gives back.
▶ Output
(nothing is printed)
📦 Memory boxes
{'Glow': 3, 'Rush': 5, 'Echo': 8}dict🧑🏫 Model answer (for the teacher)
Teacher eyes only: hide the answers before you share your screen.
The answer green = the 3 lines the student writes
plays = {"Glow": 3, "Rush": 5, "Echo": 8}del plays["Rush"]print(plays)print(plays.pop("Glow"))
What it prints
{'Glow': 3, 'Echo': 8}
3
What ✓ Check looks for
- it prints exactly:
{'Glow': 3, 'Echo': 8} 3 - In the code: Use del plays["Rush"].
- In the code: Use plays.pop("Glow").
2.4 Print the songs in alphabetical order, one per line.
▶ Output
(nothing is printed)
📦 Memory boxes
{'Rush': 5, 'Echo': 8, 'Glow': 3}dict🧑🏫 Model answer (for the teacher)
Teacher eyes only: hide the answers before you share your screen.
The answer green = the 2 lines the student writes
plays = {"Rush": 5, "Echo": 8, "Glow": 3}for song in sorted(plays): print(song)
What it prints
Echo Glow Rush
What ✓ Check looks for
- it prints exactly:
Echo Glow Rush
- In the code: Loop over sorted(plays).
2.5 Without max, loop once and print the most played song like: Top: Echo 8
▶ Output
(nothing is printed)
📦 Memory boxes
{'Rush': 5, 'Echo': 8, 'Glow': 3}dict🧑🏫 Model answer (for the teacher)
Teacher eyes only: hide the answers before you share your screen.
The answer green = the 7 lines the student writes
plays = {"Rush": 5, "Echo": 8, "Glow": 3}top = Nonebest = -1for song, n in plays.items(): if n > best: top = song best = nprint(f"Top: {top} {best}")
What it prints
Top: Echo 8
What ✓ Check looks for
- it prints exactly:
Top: Echo 8
- With
plays = {"a": 1, "b": 7}, it prints exactly:Top: b 7
- In the code: Loop over the pairs.
2.6 Add each song's weekend plays to its total (some songs are new), then print plays.
▶ Output
(nothing is printed)
📦 Memory boxes
{'Glow': 3, 'Rush': 5}dictweekend{'Rush': 2, 'Nova': 4}dict🧑🏫 Model answer (for the teacher)
Teacher eyes only: hide the answers before you share your screen.
The answer green = the 3 lines the student writes
plays = {"Glow": 3, "Rush": 5}weekend = {"Rush": 2, "Nova": 4}for song, n in weekend.items(): plays[song] = plays.get(song, 0) + nprint(plays)
What it prints
{'Glow': 3, 'Rush': 7, 'Nova': 4}
What ✓ Check looks for
- it prints exactly:
{'Glow': 3, 'Rush': 7, 'Nova': 4} - With
weekend = {"Glow": 1}, it prints exactly:{'Glow': 4, 'Rush': 5} - In the code: New songs need get(song, 0) or an in check.
Part 3 of 3 · learn, see, practise
Counting, nested dictionaries and comprehensions
Beatbox goes pro: count every word in the lyrics, keep a full record for each song (artist, year, tags) and build new dictionaries in one line.
Counting is the classic dictionary job: start with counts = {} and for each item do counts[item] = counts.get(item, 0) + 1. Each new item starts at 0, each repeat adds 1.
A value can be another dictionary, which makes a record: library["Glow"] = {"artist": "Ana", "year": 2021}. Read inside it with two keys: library["Glow"]["artist"]. A value can also be a list: {"tags": ["pop", "chill"]}.
Grouping uses lists as values: for each song, if its year is not a key yet, make an empty list, then append the song.
A dict comprehension builds a dictionary in one line: {n: n * n for n in range(1, 4)} is {1: 1, 2: 4, 3: 9}.
- Count with counts[x] = counts.get(x, 0) + 1.
- Records: one dictionary per thing, read with two keys.
JSON, the format most web apps send data in, looks exactly like nested Python dictionaries and lists.
A comprehension can filter too: {k: v for k, v in plays.items() if v > 5} keeps only the popular songs.
🧑🏫 Teacher: type this live with the class
Count, nest, build
counts = {}An empty dictionary to count into.
for word in "la la la hey la hey".split():split() makes a list of the words.
counts[word] = counts.get(word, 0) + 1New words start at 0; each one adds 1.
print(counts)Run: {'la': 4, 'hey': 2}.
song = {"title": "Glow", "artist": "Ana", "tags": ["pop", "chill"]}A record: one dictionary per song.
print(song["tags"][1])A list inside a dictionary: chill.
lengths = {t: len(t) for t in ["Glow", "Rush"]}A dict comprehension builds a dictionary in one line.
print(lengths){'Glow': 4, 'Rush': 4}.
▶ Output
(nothing is printed)
📦 Memory boxes
▶ Output
{'glow': 3, 'rush': 2, 'echo': 1}
Glow - Ana - 12 plays
Rush - Ben - 7 plays
{'artist': 'Ana', 'plays': 13}
{'Glow': 26, 'Rush': 14}📦 Memory boxes
'glow rush glow echo glow rush'strcounts{'glow': 3, 'rush': 2, 'echo': 1}dictsong'rush'strlibrary{'Glow': {'artist': 'Ana', 'plays': 13}, 'Rush': {'artist': 'Ben', 'plays': 7}}dicttitle'Rush'strinfo{'artist': 'Ben', 'plays': 7}dictdoubled{'Glow': 26, 'Rush': 14}dictAdd a third song record to library and run it again. Then filter: {t: i for t, i in library.items() if i["plays"] > 10}.
Puzzle break: counting and nesting
Read it the way Python does, line by line, before anyone runs it.
- Puzzle 1: put the lines in order
- Puzzle 2: fill the gap
- Puzzle 3: say what happens before you run it
Practise it
Start with the warm-up and go as far as you can. The stretch questions are meant to be hard.
3.1 Print the artist of "Glow" from the nested dictionary.
▶ Output
(nothing is printed)
📦 Memory boxes
{'Glow': {'artist': 'Ana', 'year': 2021}, 'Rush': {'artist': 'Ben', 'year': 2023}}dict🧑🏫 Model answer (for the teacher)
Teacher eyes only: hide the answers before you share your screen.
The answer green = the 1 line the student writes
library = {"Glow": {"artist": "Ana", "year": 2021}, "Rush": {"artist": "Ben", "year": 2023}}print(library["Glow"]["artist"])
What it prints
Ana
What ✓ Check looks for
- it prints exactly:
Ana
- In the code: Use two keys: library["Glow"]["artist"].
3.2 Make a dictionary of squares for 1 to 5 with a dict comprehension and print it.
▶ Output
(nothing is printed)
📦 Memory boxes
🧑🏫 Model answer (for the teacher)
Teacher eyes only: hide the answers before you share your screen.
The answer green = the 2 lines the student writes
squares = {n: n * n for n in range(1, 6)}print(squares)
What it prints
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
What ✓ Check looks for
- it prints exactly:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25} - In the code: Write {n: n * n for n in range(1, 6)}.
3.3 Count each letter of the word with a dictionary and print it.
▶ Output
(nothing is printed)
📦 Memory boxes
'banana'str🧑🏫 Model answer (for the teacher)
Teacher eyes only: hide the answers before you share your screen.
The answer green = the 4 lines the student writes
word = "banana"counts = {}for letter in word: counts[letter] = counts.get(letter, 0) + 1print(counts)
What it prints
{'b': 1, 'a': 3, 'n': 2}
What ✓ Check looks for
- it prints exactly:
{'b': 1, 'a': 3, 'n': 2} - With
word = "aab", it prints exactly:{'a': 2, 'b': 1} - In the code: Use counts.get(letter, 0) + 1.
3.4 Add "Echo" by "Cy" from 2024 to the library, then print every song with its artist, like Glow by Ana.
▶ Output
(nothing is printed)
📦 Memory boxes
{'Glow': {'artist': 'Ana', 'year': 2021}, 'Rush': {'artist': 'Ben', 'year': 2023}}dict🧑🏫 Model answer (for the teacher)
Teacher eyes only: hide the answers before you share your screen.
The answer green = the 3 lines the student writes
library = {"Glow": {"artist": "Ana", "year": 2021}, "Rush": {"artist": "Ben", "year": 2023}}library["Echo"] = {"artist": "Cy", "year": 2024}for title, info in library.items(): print(title, "by", info["artist"])
What it prints
Glow by Ana Rush by Ben Echo by Cy
What ✓ Check looks for
- it prints exactly:
Glow by Ana Rush by Ben Echo by Cy
- In the code: Add the record with library["Echo"] = {...}.
3.5 Group the songs by year: build a dictionary from each year to a list of its songs, then print it.
▶ Output
(nothing is printed)
📦 Memory boxes
{'Glow': 2021, 'Rush': 2023, 'Echo': 2021, 'Nova': 2023, 'Drift': 2022}dict🧑🏫 Model answer (for the teacher)
Teacher eyes only: hide the answers before you share your screen.
The answer green = the 6 lines the student writes
years = {"Glow": 2021, "Rush": 2023, "Echo": 2021, "Nova": 2023, "Drift": 2022}groups = {}for song, year in years.items(): if year not in groups: groups[year] = [] groups[year].append(song)print(groups)
What it prints
{2021: ['Glow', 'Echo'], 2023: ['Rush', 'Nova'], 2022: ['Drift']}
What ✓ Check looks for
- it prints exactly:
{2021: ['Glow', 'Echo'], 2023: ['Rush', 'Nova'], 2022: ['Drift']} - With
years = {"a": 1, "b": 1}, it prints exactly:{1: ['a', 'b']} - In the code: Append each song to its year's list.
3.6 Count the words in the lower-case text and print each word that appears more than once, in A to Z order, like: the 3
▶ Output
(nothing is printed)
📦 Memory boxes
'The beat drops and the crowd jumps and the night goes on'str🧑🏫 Model answer (for the teacher)
Teacher eyes only: hide the answers before you share your screen.
The answer green = the 6 lines the student writes
text = "The beat drops and the crowd jumps and the night goes on"counts = {}for word in text.lower().split(): counts[word] = counts.get(word, 0) + 1for word in sorted(counts): if counts[word] > 1: print(word, counts[word])
What it prints
and 2 the 3
What ✓ Check looks for
- it prints exactly:
and 2 the 3
- With
text = "a b A", it prints exactly:a 2
- In the code: Use text.lower() first.
Watch out
Common mistakes
Reading a missing key with []
plays["Nova"] crashes with KeyError. Use plays.get("Nova", 0) or check "Nova" in plays first.
Thinking in checks the values
in looks at the keys only. To search the values, use x in plays.values().
Looping and getting only keys
for k, v in d: fails. Use for k, v in d.items():
Counting without a start value
counts[w] += 1 fails the first time; write counts[w] = counts.get(w, 0) + 1.
Using a list as a key
Keys must not change, so a list can't be a key. Use a tuple.
Class activity 1 of 3
Beatbox play counter
Count how many times each song was played in the listening log, then find the top song. When it works it prints:
{'Glow': 3, 'Rush': 2, 'Echo': 1}
Top song: Glow (3 plays)
- Make an empty dictionary called counts.
- Loop over the log and add 1 to each song with get.
- Print counts.
- Find the top song and print it in the format shown.
▶ Output
(nothing is printed)
📦 Memory boxes
['Glow', 'Rush', 'Glow', 'Echo', 'Glow', 'Rush']listHint
counts.get(song, 0) is 0 the first time a song appears, so + 1 starts it at 1.
🧑🏫 Model answer (for the teacher)
Teacher eyes only: hide the answers before you share your screen.
The answer green = the 6 lines the student writes
# ===== Beatbox play counter =====log = ["Glow", "Rush", "Glow", "Echo", "Glow", "Rush"]counts = {}for song in log: counts[song] = counts.get(song, 0) + 1print(counts)top = max(counts, key=counts.get)print(f"Top song: {top} ({counts[top]} plays)")
What it prints
{'Glow': 3, 'Rush': 2, 'Echo': 1}
Top song: Glow (3 plays)
What ✓ Check looks for
- it prints exactly:
{'Glow': 3, 'Rush': 2, 'Echo': 1} Top song: Glow (3 plays) - With
log = ["a", "b", "b"], it prints exactly:{'a': 1, 'b': 2} Top song: b (2 plays) - In the code: Step 1: count with counts.get(song, 0) + 1.
If they're stuck, say
counts.get(song, 0) is 0 the first time a song appears, so + 1 starts it at 1.
Class activity 2 of 3
Song lookup service
Write the two functions behind Beatbox's search box. When it works it prints:
Glow by Ana
Not found: Nova
Nova by Dee
3 songs
- Write lookup(title): return 'title by artist' if the title is in the library, otherwise 'Not found: title'.
- Write add(title, artist) that adds a pair to the library.
- Look up Glow and Nova, add Nova, look it up again, then print how many songs there are.
▶ Output
(nothing is printed)
📦 Memory boxes
{'Glow': 'Ana', 'Rush': 'Ben'}dictHint
Return as soon as you know the answer: inside the if, return the found message; after it, return the not-found one.
🧑🏫 Model answer (for the teacher)
Teacher eyes only: hide the answers before you share your screen.
The answer green = the 11 lines the student writes
# ===== Song lookup service =====library = {"Glow": "Ana", "Rush": "Ben"} def lookup(title): if title in library: return f"{title} by {library[title]}" return f"Not found: {title}" def add(title, artist): library[title] = artist print(lookup("Glow"))print(lookup("Nova"))add("Nova", "Dee")print(lookup("Nova"))print(len(library), "songs")
What it prints
Glow by Ana Not found: Nova Nova by Dee 3 songs
What ✓ Check looks for
- it prints exactly:
Glow by Ana Not found: Nova Nova by Dee 3 songs
- In the code: Step 1: write lookup.
- In the code: Check with if title in library:
If they're stuck, say
Return as soon as you know the answer: inside the if, return the found message; after it, return the not-found one.
Class activity 3 of 3
Class report card
Turn a dictionary of marks into a report: a grade letter for each student (A from 85, B from 70, else C), the class average and a ranking. When it works it prints:
Ana: 82 B
Ben: 67 C
Cy: 91 A
Dee: 74 B
Average: 78.5
Ranking: ['Cy', 'Ana', 'Dee', 'Ben']
- Loop over marks.items() and choose each grade letter with if, elif and else.
- Print the average: sum of the values ÷ the number of students.
- Print the names sorted by mark, highest first.
▶ Output
(nothing is printed)
📦 Memory boxes
{'Ana': 82, 'Ben': 67, 'Cy': 91, 'Dee': 74}dictHint
sorted(marks, key=marks.get) sorts the names by their marks; reverse=True puts the highest first.
🧑🏫 Model answer (for the teacher)
Teacher eyes only: hide the answers before you share your screen.
The answer green = the 10 lines the student writes
# ===== Class report card =====marks = {"Ana": 82, "Ben": 67, "Cy": 91, "Dee": 74}for name, m in marks.items(): if m >= 85: letter = "A" elif m >= 70: letter = "B" else: letter = "C" print(f"{name}: {m} {letter}")print("Average:", sum(marks.values()) / len(marks))print("Ranking:", sorted(marks, key=marks.get, reverse=True))
What it prints
Ana: 82 B Ben: 67 C Cy: 91 A Dee: 74 B Average: 78.5 Ranking: ['Cy', 'Ana', 'Dee', 'Ben']
What ✓ Check looks for
- it prints exactly:
Ana: 82 B Ben: 67 C Cy: 91 A Dee: 74 B Average: 78.5 Ranking: ['Cy', 'Ana', 'Dee', 'Ben']
- With
marks = {"Zed": 85, "Yo": 69}, it prints exactly:Zed: 85 A Yo: 69 C Average: 77.0 Ranking: ['Zed', 'Yo']
- In the code: Step 1: loop over marks.items().
If they're stuck, say
sorted(marks, key=marks.get) sorts the names by their marks; reverse=True puts the highest first.
After class · project
My Beatbox music library
Build a small music library in a dictionary of records: add songs, play them (which counts the plays), and print a top-songs report.
What to make: A program with no errors that keeps a library of song records in a dictionary, with add_song, play and report functions.
Stretch: Add tags to each record (a list), and a by_tag(tag) function that returns every song with that tag.
How it is marked
| Look for | Done well when |
|---|---|
| Runs | No red error when you press Run |
| Dictionaries | A dictionary of records, read and changed with two keys |
| Safety | play() never crashes on a missing song |
| Report | Songs sorted by plays, highest first, with bars |
Starter code to take home
Press Copy and paste it into the editor at home, or work on it right here.
▶ Output
(nothing is printed)
📦 Memory boxes
{'Glow': {'artist': 'Ana', 'plays': 2}, 'Rush': {'artist': 'Ben', 'plays': 0}}dict🔑 Show one possible solution (try it yourself first!)
▶ Output
No such song: Nova Echo by Cy: ### 3 Glow by Ana: ## 2 Rush by Ben: # 1
📦 Memory boxes
{'Glow': {'artist': 'Ana', 'plays': 2}, 'Rush': {'artist': 'Ben', 'plays': 1}, 'Echo': {'artist': 'Cy', 'plays': 3}}dictt'Nova'strHomework
Practise at home
Each one checks itself. Or print the practice sheet.
1. Make a dictionary capitals with "France": "Paris" and "Japan": "Tokyo", add "Kenya": "Nairobi", then print the capital of Japan.
▶ Output
(nothing is printed)
📦 Memory boxes
🧑🏫 Model answer (for the teacher)
Teacher eyes only: hide the answers before you share your screen.
The answer green = the 3 lines the student writes
capitals = {"France": "Paris", "Japan": "Tokyo"}capitals["Kenya"] = "Nairobi"print(capitals["Japan"])
What it prints
Tokyo
What ✓ Check looks for
- it prints exactly:
Tokyo
- In the code: Add Kenya with capitals["Kenya"] = "Nairobi".
2. Print each item and its price on its own line, like apple $1.2
▶ Output
(nothing is printed)
📦 Memory boxes
{'apple': 1.2, 'milk': 0.99}dict🧑🏫 Model answer (for the teacher)
Teacher eyes only: hide the answers before you share your screen.
The answer green = the 2 lines the student writes
prices = {"apple": 1.2, "milk": 0.99}for item, price in prices.items(): print(item, "$" + str(price))
What it prints
apple $1.2 milk $0.99
What ✓ Check looks for
- it prints exactly:
apple $1.2 milk $0.99
- In the code: Loop with prices.items().
3. Print the total cost of the shopping list: each item's price times how many you buy.
▶ Output
(nothing is printed)
📦 Memory boxes
{'apple': 0.5, 'bread': 2.0, 'milk': 1.25}dictbuy{'apple': 6, 'milk': 2}dict🧑🏫 Model answer (for the teacher)
Teacher eyes only: hide the answers before you share your screen.
The answer green = the 4 lines the student writes
prices = {"apple": 0.5, "bread": 2.0, "milk": 1.25}buy = {"apple": 6, "milk": 2}total = 0for item, n in buy.items(): total += prices[item] * nprint(total)
What it prints
5.5
What ✓ Check looks for
- it prints exactly:
5.5
- With
buy = {"bread": 3}, it prints exactly:6.0
- In the code: Loop over buy.
4. Count how many words of each length are in the text, then print each length and its count in order of length, like 3: 4
▶ Output
(nothing is printed)
📦 Memory boxes
'the quick brown fox jumps over the lazy dog'str🧑🏫 Model answer (for the teacher)
Teacher eyes only: hide the answers before you share your screen.
The answer green = the 6 lines the student writes
text = "the quick brown fox jumps over the lazy dog"counts = {}for word in text.split(): n = len(word) counts[n] = counts.get(n, 0) + 1for n in sorted(counts): print(f"{n}: {counts[n]}")
What it prints
3: 4 4: 2 5: 3
What ✓ Check looks for
- it prints exactly:
3: 4 4: 2 5: 3
- With
text = "aa b", it prints exactly:1: 1 2: 1
- In the code: Print in order with sorted().
5. Turn the favourites inside out: build a dictionary from each colour to a list of the people who chose it, then print it.
▶ Output
(nothing is printed)
📦 Memory boxes
{'Ana': 'blue', 'Ben': 'red', 'Cy': 'blue'}dict🧑🏫 Model answer (for the teacher)
Teacher eyes only: hide the answers before you share your screen.
The answer green = the 6 lines the student writes
fav = {"Ana": "blue", "Ben": "red", "Cy": "blue"}by_colour = {}for name, colour in fav.items(): if colour not in by_colour: by_colour[colour] = [] by_colour[colour].append(name)print(by_colour)
What it prints
{'blue': ['Ana', 'Cy'], 'red': ['Ben']}
What ✓ Check looks for
- it prints exactly:
{'blue': ['Ana', 'Cy'], 'red': ['Ben']} - With
fav = {"x": "y"}, it prints exactly:{'y': ['x']} - In the code: Append each name to its colour's list.
🔥 Challenge round · finished early?
The hardest questions of the lesson, no notes
Cover the notes and try these from memory. They are meant to make you think hard: draw, try small cases, and check your answer.
- Stretch task 1: Write plays_of(song) that returns the song's plays, or -1 when it is not in the dictionary (check with in). Print plays_of("Rush") and plays_of("Nova").
- Stretch task 1: Swap keys and values: build a new dictionary that maps each number to its song, then print it.
- Stretch task 2: Without max, loop once and print the most played song like: Top: Echo 8
- Stretch task 2: Add each song's weekend plays to its total (some songs are new), then print plays.
- Stretch task 3: Group the songs by year: build a dictionary from each year to a list of its songs, then print it.
- Stretch task 3: Count the words in the lower-case text and print each word that appears more than once, in A to Z order, like: the 3
🧠 Think-hard question
Write merge_counts(a, b) that returns a new dictionary with the counts of both added together, without changing a or b. Then make it work for any number of dictionaries.
Talk it through or use the drawing board. There is more than one way to get there.
Quiz · 8 questions
Final quiz: check what you learned
Pick an answer to see if it is right and why. Your best score is saved on this device.
🖨 Print what we learned
Make a worksheet from this lesson
Pick what to practise, then print it or choose Save as PDF in the print window to download it.
For parents and teachers
The 60-minute lesson plan
Use it as it is, or stretch any part over two sessions. Each row links to the part of the page you need.
| Time | Part | The teacher | The learner |
|---|---|---|---|
| 0–3 min | Warm-up | Ask the question and wait for a guess before any hint. | Guess, then explain. |
| 3–8 min | Warm-up games | Play three or four games. Ask for a reason each time. | Vote and say why. |
| 8–17 min | Dictionaries: keys and values | Type-along first: type each line, say the words, run it. Show the example, then do the puzzle break together before the practice. | Type along, crack the puzzles, then practise. |
| 17–26 min | Looping and dictionary methods | Type-along first: type each line, say the words, run it. Show the example, then do the puzzle break together before the practice. | Type along, crack the puzzles, then practise. |
| 26–35 min | Counting, nested dictionaries and comprehensions | Type-along first: type each line, say the words, run it. Show the example, then do the puzzle break together before the practice. | Type along, crack the puzzles, then practise. |
| 35–42 min | Beatbox play counter | Show the boilerplate and read the numbered steps. Let them press Check often. | Follow the steps. |
| 42–49 min | Song lookup service | Do step 1 together, then let them finish. | Finish the activity. |
| 49–54 min | Class report card | If time is short, set it as homework. | Try the challenge. |
| 54–59 min | Quiz | Read each question aloud. Vote, then check. | Answer and read why. |
| 59–60 min | Set the after-class project | Open the project and agree a due date. | Copy the boilerplate. |
Questions to ask
- What is the difference between a list and a dictionary?
- Why can't a list be a key?
- What do in and get() protect you from?
- How do you count things with a dictionary?
If it feels hard
Draw a two-column table, keys on the left and values on the right, and update it by hand while reading each line aloud before running the code.
If it feels easy
Write merge_counts(a, b) that returns a new dictionary with the counts of both added together, without changing a or b. Then make it work for any number of dictionaries.
FAQ
All about dictionaries: questions
What is a dictionary in Python?
A collection of key: value pairs in curly brackets, like {"Glow": 3}. You look values up by key instead of by position, and keys are unique.
What is the difference between d[key] and d.get(key)?
d[key] stops with KeyError when the key is missing; d.get(key) gives None (or a default you choose) instead.
Do dictionaries keep their order?
Yes: since Python 3.7 a dictionary remembers the order its keys were added.
Start a conversation
Want a teacher to take this class?
Tell us the learner's age and level. A teacher from our network teaches with these lessons; we confirm timing and price first.
- Tell us the learner’s age or grade and goals
- We’ll suggest a suitable class or learning path
- We’ll confirm format, timing and fees with a parent or guardian