🗂️ 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.

🎯 Practice mode⚔️ Boss battle🖨 Print a worksheet
Illustration of a cute pastel robot dancing
Illustration: andremsdesign / Pixabay

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.

See the teacher's plan
  1. Warm-up3 min
  2. Warm-up games5 min
  3. Dictionaries: keys and values9 min
  4. Looping and dictionary methods9 min
  5. Counting, nested dictionaries and comprehensions9 min
  6. Beatbox play counter7 min
  7. Song lookup service7 min
  8. Class report card5 min
  9. Quiz5 min
  10. 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.

More warm-ups for every class →

🎮 Warm-up games · 5 quick games

Play with Bolt the robot

Five minutes in the Beatbox studio. Vote, say why, then show the answer.

  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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.

  1. 🔒

    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.

  2. 🔧

    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.

  3. 🛠️

    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.

Remember!
  • d[key] reads, d[key] = value adds or changes.
  • Missing keys: use in to check, or get(key, default).
📝 Notes

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

  1. plays = {"Glow": 3, "Rush": 5}

    Curly brackets; each pair is key: value.

  2. print(plays["Rush"])

    Look up by key, not by position: 5.

  3. plays["Echo"] = 8

    A new key adds a pair.

  4. plays["Glow"] += 1

    An existing key changes its value: Glow is now 4.

  5. print(plays)

    Run it: {'Glow': 4, 'Rush': 5, 'Echo': 8}.

  6. print(len(plays), "Nova" in plays)

    3 pairs; in checks the keys: False.

  7. print(plays.get("Nova", 0))

    get gives a default instead of an error: 0.

Type here

▶ Output

(nothing is printed)

📦 Memory boxes

No variables yet
Example: run it, then change it

▶ Output

Songs: 2
Glow is by Ana
{'Glow': 'Ana', 'Rush': 'Bea', 'Echo': 'Cy'}
Nova is not in the library
unknown artist

📦 Memory boxes

library{'Glow': 'Ana', 'Rush': 'Bea', 'Echo': 'Cy'}dictsong'Nova'str

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

  1. Puzzle 1: say what happens before you run it
  2. Puzzle 2: say what happens before you run it
  3. 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.

Warm-up

1.1 Make a dictionary called plays with "Glow": 3 and "Rush": 5, then print it.

Task 1.1

▶ Output

(nothing is printed)

📦 Memory boxes

No variables yet
🧑‍🏫 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 = {...}.
Warm-up

1.2 Print how many plays "Echo" has, using its key.

Task 1.2

▶ Output

(nothing is printed)

📦 Memory boxes

plays{'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"].
Core

1.3 Add "Drift" with 0 plays, add 1 to "Glow", then print the dictionary.

Task 1.3

▶ Output

(nothing is printed)

📦 Memory boxes

plays{'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.
Core

1.4 Print the plays for "Nova" using get with 0 for a missing song, then the same for "Rush".

Task 1.4

▶ Output

(nothing is printed)

📦 Memory boxes

plays{'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).
Stretch 🔥

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").

Task 1.5

▶ Output

(nothing is printed)

📦 Memory boxes

plays{'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:
Stretch 🔥

1.6 Swap keys and values: build a new dictionary that maps each number to its song, then print it.

Task 1.6

▶ Output

(nothing is printed)

📦 Memory boxes

codes{'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.

Remember!
  • for k, v in d.items(): reads keys and values together.
  • del removes; pop removes and returns; update merges.
📝 Notes

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

  1. chart = {"Glow": 4, "Rush": 5, "Echo": 8}

    Three songs and their plays.

  2. for song in chart:

    Looping over a dictionary visits its keys.

  3. print(song, chart[song])

    Use the key to get each value.

  4. for song, n in chart.items():

    items() gives each key and value together.

  5. print(song, "#" * n)

    A tiny bar chart: one # per play.

  6. del chart["Rush"]

    del removes a key and its value.

  7. print(sorted(chart), sum(chart.values()))

    Keys in A to Z order, and the total of the values.

Type here

▶ Output

(nothing is printed)

📦 Memory boxes

No variables yet
Example: run it, then change it

▶ 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

plays{'Glow': 12, 'Rush': 8, 'Echo': 15, 'Drift': 9, 'Nova': 3}dicttotal43intsong'Rush'strn9int

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

  1. Puzzle 1: say what happens before you run it
  2. Puzzle 2: find the bug
  3. 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.

Warm-up

2.1 Print every song and its plays on its own line, like Glow 3, using items().

Task 2.1

▶ Output

(nothing is printed)

📦 Memory boxes

plays{'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():
Warm-up

2.2 Print the total number of plays, using values().

Task 2.2

▶ Output

(nothing is printed)

📦 Memory boxes

plays{'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().
Core

2.3 Remove "Rush" with del and print the dictionary, then remove "Glow" with pop and print the plays it gives back.

Task 2.3

▶ Output

(nothing is printed)

📦 Memory boxes

plays{'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").
Core

2.4 Print the songs in alphabetical order, one per line.

Task 2.4

▶ Output

(nothing is printed)

📦 Memory boxes

plays{'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).
Stretch 🔥

2.5 Without max, loop once and print the most played song like: Top: Echo 8

Task 2.5

▶ Output

(nothing is printed)

📦 Memory boxes

plays{'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.
Stretch 🔥

2.6 Add each song's weekend plays to its total (some songs are new), then print plays.

Task 2.6

▶ Output

(nothing is printed)

📦 Memory boxes

plays{'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}.

Remember!
  • Count with counts[x] = counts.get(x, 0) + 1.
  • Records: one dictionary per thing, read with two keys.
📝 Notes

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

  1. counts = {}

    An empty dictionary to count into.

  2. for word in "la la la hey la hey".split():

    split() makes a list of the words.

  3. counts[word] = counts.get(word, 0) + 1

    New words start at 0; each one adds 1.

  4. print(counts)

    Run: {'la': 4, 'hey': 2}.

  5. song = {"title": "Glow", "artist": "Ana", "tags": ["pop", "chill"]}

    A record: one dictionary per song.

  6. print(song["tags"][1])

    A list inside a dictionary: chill.

  7. lengths = {t: len(t) for t in ["Glow", "Rush"]}

    A dict comprehension builds a dictionary in one line.

  8. print(lengths)

    {'Glow': 4, 'Rush': 4}.

Type here

▶ Output

(nothing is printed)

📦 Memory boxes

No variables yet
Example: run it, then change it

▶ 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

text'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}dict

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

  1. Puzzle 1: put the lines in order
  2. Puzzle 2: fill the gap
  3. 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.

Warm-up

3.1 Print the artist of "Glow" from the nested dictionary.

Task 3.1

▶ Output

(nothing is printed)

📦 Memory boxes

library{'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"].
Warm-up

3.2 Make a dictionary of squares for 1 to 5 with a dict comprehension and print it.

Task 3.2

▶ Output

(nothing is printed)

📦 Memory boxes

No variables yet
🧑‍🏫 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)}.
Core

3.3 Count each letter of the word with a dictionary and print it.

Task 3.3

▶ Output

(nothing is printed)

📦 Memory boxes

word'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.
Core

3.4 Add "Echo" by "Cy" from 2024 to the library, then print every song with its artist, like Glow by Ana.

Task 3.4

▶ Output

(nothing is printed)

📦 Memory boxes

library{'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"] = {...}.
Stretch 🔥

3.5 Group the songs by year: build a dictionary from each year to a list of its songs, then print it.

Task 3.5

▶ Output

(nothing is printed)

📦 Memory boxes

years{'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.
Stretch 🔥

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

Task 3.6

▶ Output

(nothing is printed)

📦 Memory boxes

text'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)

  1. Make an empty dictionary called counts.
  2. Loop over the log and add 1 to each song with get.
  3. Print counts.
  4. Find the top song and print it in the format shown.
Your code

▶ Output

(nothing is printed)

📦 Memory boxes

log['Glow', 'Rush', 'Glow', 'Echo', 'Glow', 'Rush']list
Hint

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

  1. Write lookup(title): return 'title by artist' if the title is in the library, otherwise 'Not found: title'.
  2. Write add(title, artist) that adds a pair to the library.
  3. Look up Glow and Nova, add Nova, look it up again, then print how many songs there are.
Your code

▶ Output

(nothing is printed)

📦 Memory boxes

library{'Glow': 'Ana', 'Rush': 'Ben'}dict
Hint

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']

  1. Loop over marks.items() and choose each grade letter with if, elif and else.
  2. Print the average: sum of the values ÷ the number of students.
  3. Print the names sorted by mark, highest first.
Your code

▶ Output

(nothing is printed)

📦 Memory boxes

marks{'Ana': 82, 'Ben': 67, 'Cy': 91, 'Dee': 74}dict
Hint

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 forDone well when
RunsNo red error when you press Run
DictionariesA dictionary of records, read and changed with two keys
Safetyplay() never crashes on a missing song
ReportSongs 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.

Project starter

▶ Output

(nothing is printed)

📦 Memory boxes

library{'Glow': {'artist': 'Ana', 'plays': 2}, 'Rush': {'artist': 'Ben', 'plays': 0}}dict
🔑 Show one possible solution (try it yourself first!)
One possible solution

▶ Output

No such song: Nova
Echo by Cy: ### 3
Glow by Ana: ## 2
Rush by Ben: # 1

📦 Memory boxes

library{'Glow': {'artist': 'Ana', 'plays': 2}, 'Rush': {'artist': 'Ben', 'plays': 1}, 'Echo': {'artist': 'Cy', 'plays': 3}}dictt'Nova'str

Homework

Practise at home

Each one checks itself. Or print the practice sheet.

Warm-up

1. Make a dictionary capitals with "France": "Paris" and "Japan": "Tokyo", add "Kenya": "Nairobi", then print the capital of Japan.

Homework 1

▶ Output

(nothing is printed)

📦 Memory boxes

No variables yet
🧑‍🏫 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".
Core

2. Print each item and its price on its own line, like apple $1.2

Homework 2

▶ Output

(nothing is printed)

📦 Memory boxes

prices{'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().
Core

3. Print the total cost of the shopping list: each item's price times how many you buy.

Homework 3

▶ Output

(nothing is printed)

📦 Memory boxes

prices{'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.
Stretch 🔥

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

Homework 4

▶ Output

(nothing is printed)

📦 Memory boxes

text'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().
Stretch 🔥

5. Turn the favourites inside out: build a dictionary from each colour to a list of the people who chose it, then print it.

Homework 5

▶ Output

(nothing is printed)

📦 Memory boxes

fav{'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.

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

1What does this show?
d = {"Glow": 3}
print(d["Glow"])
Show the answer

3. The key Glow looks up its value, 3.

2What does this show?
d = {"Glow": 3}
print(d.get("Nova"))
Show the answer

None. get gives None for a missing key when no default is given.

3What does this show?
d = {"a": 1, "b": 2}
d["a"] = 5
print(d)
Show the answer

{'a': 5, 'b': 2}. Setting an existing key changes its value and keeps its place.

4What does this show?
d = {"x": 1, "y": 2}
d["z"] = 3
print(len(d))
Show the answer

3. Adding the new key z makes three pairs.

5What does this show?
d = {"a": 1}
print(1 in d)
Show the answer

False. in checks the keys only, and 1 is a value, not a key.

6What does this show?
d = {"a": 1, "b": 2}
print(list(d))
Show the answer

['a', 'b']. list(d) gives the keys.

7What does this show?
c = {}
c["a"] += 1
print(c)
Show the answer

KeyError. c['a'] += 1 needs a value to add to, and there is none yet.

8What does this show?
sq = {n: n * n for n in [2, 3]}
print(sq)
Show the answer

{2: 4, 3: 9}. A dict comprehension makes key: value pairs.

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

Include
Options

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.

TimePartThe teacherThe learner
0–3 minWarm-upAsk the question and wait for a guess before any hint.Guess, then explain.
3–8 minWarm-up gamesPlay three or four games. Ask for a reason each time.Vote and say why.
8–17 minDictionaries: keys and valuesType-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 minLooping and dictionary methodsType-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 minCounting, nested dictionaries and comprehensionsType-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 minBeatbox play counterShow the boilerplate and read the numbered steps. Let them press Check often.Follow the steps.
42–49 minSong lookup serviceDo step 1 together, then let them finish.Finish the activity.
49–54 minClass report cardIf time is short, set it as homework.Try the challenge.
54–59 minQuizRead each question aloud. Vote, then check.Answer and read why.
59–60 minSet the after-class projectOpen 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

For a child’s class, please have a parent or guardian send the enquiry. Avoid sharing passwords or sensitive personal details.

We’ll use your details only to respond to this request.

Chat on WhatsApp
Esc

Try