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 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 |
| Round | item | inventory[item] | total after the round |
|---|---|---|---|
| 1 | water | 12 | 12 |
| 2 | oats | 8 | 20 |
| 3 | tape | 3 | 23 |
inventory = {"water": 12, "oats": 2, "tape": 3, "lamps": 9, "rope": 4}
for item in inventory:
if inventory[item] < 5:
print("Low:", item) crew = {"Rocket": 3, "Raven": 5, "Kai": 2}
for name in crew:
print(name, crew[name] * 2) | Statement | True 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. | ? |
Great reporting! Tomorrow you will check if a key is there before you look it up.