← Back to course
Code Crew G4 / Week 07 / Thursday
4/6
Week 07 Β· Dictionaries

Thursday

Loop over a dictionary
// Look it up by name
⏱ about 15 min

Thursday: Loop over a dictionary

It is time for the weekly inventory report. Rocket wants every item and its count on the screen, plus a total. He starts writing one print line for each key.

"We did this with lists," Raven says. "What do you notice? A loop could visit each one."

Rocket frowns. "But what does the loop variable hold, the key or the value?" Nova blinks twice. "Interesting question! Would you like a hint? The loop gives you keys. A key can look up its value."

A for loop visits the keys

A for loop over a dictionary visits each key, in the order the pairs were added.

Inside the loop, use the key to look up the value.

inventory = {"water": 12, "oats": 8, "tape": 3}
total = 0
for item in inventory:
    print(item, inventory[item])
    total = total + inventory[item]
print("Total:", total)
The screen shows
water 12
oats 8
tape 3
Total: 23
Rounditeminventory[item]total after the round
1water1212
2oats820
3tape323
inventory = {"water": 12, "oats": 2, "tape": 3, "lamps": 9, "rope": 4}
for item in inventory:
    if inventory[item] < 5:
        print("Low:", item)
PUT THE SCREEN LINES IN ORDER FOR THE PROGRAM ABOVE
  • ?Low: tape
  • ?Low: rope
  • ?Low: oats
WHY THIS EXERCISEA loop plus an if finds every low supply, however long the list.
Change < 5 to < 10. How many Low: lines show now?
WHY THIS EXERCISEChanging the rule changes the report. Testing a new rule by hand is good practice.
KEY OR VALUE?
  • Read the question.
  • Tap your answer.
In for item in inventory:, what does item hold each round?
Try it
Read the inventory report out loud like a loop.
Say the key, then its value, for each pair.

Practice lab: double the shifts

crew = {"Rocket": 3, "Raven": 5, "Kai": 2}
for name in crew:
    print(name, crew[name] * 2)
What number shows on line 1?
What number shows on line 2?
Which name shows on the last line?
How many rounds does the loop run?
LOOP CHECK
  • Read the question.
  • Tap your answer.
In for name in crew:, what does name hold in round 2?
How do you get the value inside the loop?
In what order does the loop visit the keys?
StatementTrue or false?
The loop visits each key once.?
The loop variable holds a value.?
crew[name] looks up the value for that key.?
A dictionary loop can keep a running total.?
WHY THIS EXERCISEKeys come from the loop. Values come from looking them up.
A loop totals the values of {"a": 4, "b": 7, "c": 9}. What is the total?
WHY THIS EXERCISEThe loop looks up each value and adds it, just like a list total.

Great reporting! Tomorrow you will check if a key is there before you look it up.

← Wednesday