python · level 2 · unit 1 · lesson 3
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Loop through a dictionary to visit every pair.
A for loop over a dictionary visits each key, in the order the keys were added. Inside the loop, square brackets fetch the value that goes with each key.
Often you want both at once. hands over each key with its value, and a loop with two variables catches them: the key lands in the first, the value in the second.
hands over the values on their own, and adds up a group of numbers. Together they total a whole dictionary in one line.
steps = {"Mon": 4200, "Tue": 6100, "Wed": 5300}
for day, count in steps.items():
print(f"{day}: {count} steps")
print(f"Total: {sum(steps.values())} steps") for key in d gives you only the keys, while .items() gives keys and values together.
guess first
Pocket money for the week. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
jobs = {"wash car": 5, "walk dog": 3, "tidy room": 2}
total = 0
for job in jobs:
total = total + jobs[job]
print(total)
print(sum(jobs.values()) == total)
your turn
Your turn. Print your reading log.
Fill in three books and how many pages you read of each. Then pick the right method in each of the last two blanks: one for pairs, one for values.
fix it
The team sheet is back to front. Can you fix it?
- The names and numbers have swapped places. Which loop variable catches the key?
.items()always hands over the key first, then the value. Here the keys are the names.- Change line 2 to for player, number in shirts.items(): and run.
nailed it
you visited every pair in the dictionary. :D
- Looping over a dictionary visits each key in order.
.items()hands over each key together with its value.sum(d.values())adds up every value in one go.
new words in your collection
- .items()
- .values()
- sum
This lesson isn’t saved. A free account remembers every lesson you finish.