The crew has tagged every task this week as build, test or idea. The flight director asks a simple question: how many of each?
Rocket starts three counters, then remembers that new tags appear every week. "I cannot make a variable for every tag forever," he says.
Raven thinks about Thursday. "What do you notice?" she asks. "Each tag is a name, and each count is a number. A name with a number sounds like a dictionary."
Nova sorts glowing tags into piles in the air, and a number appears above each pile. "I found a pattern," she says. "Look up the tag. If it is new, start at zero. Then add one."
Rocket writes one line that does exactly that.
counts.get(tag, 0) gives the current count, or 0 if the tag is new. Adding 1 and storing it back counts one more. One line handles every tag, even ones you have never seen.
The items() method gives each key and value as a pair, so a for loop can use both.
# tag_count.py
tags = ["build", "test", "idea", "build", "test", "build"]
counts = {}
for tag in tags:
counts[tag] = counts.get(tag, 0) + 1
for tag, number in counts.items():
print(f"{tag}: {number}") build: 3 test: 2 idea: 1
Real data often looks like a list of records, where each record is a dictionary. This is exactly the shape the Mission Log will use in week 11.
Inside an f-string that uses double quotes, use single quotes around the key, like entry['day'].
# log_preview.py
log = [
{"day": 1, "tag": "build", "text": "Built the launch clock"},
{"day": 2, "tag": "test", "text": "Tested the fuel gauge"},
{"day": 3, "tag": "build", "text": "Added the docking game"},
]
for entry in log:
print(f"Day {entry['day']} [{entry['tag']}] {entry['text']}")
print(len(log), "entries") Day 1 [build] Built the launch clock Day 2 [test] Tested the fuel gauge Day 3 [build] Added the docking game 3 entries
items() gives each key and value together. That makes it easy to add up the values and check each one as you go.
# fuel_tanks.py
tanks = {"A": 40, "B": 75, "C": 20}
total = 0
for name, level in tanks.items():
total = total + level
if level < 30:
print(f"Tank {name} is low")
print("Total fuel:", total) | Statement | True or false? |
|---|---|
| for k, v in d.items() gives each key and its value. | ? |
| counts.get(tag, 0) gives 0 for a tag never seen before. | ? |
| A list can hold dictionaries as its items. | ? |
| log[0]["tag"] reads the tag of the last entry. | ? |
Lists of dictionaries can hold almost any information. You now know the data shape at the heart of Mission Log. Tomorrow is a Crew Quest.