The flight board in the main hall needs to show every launch with its time and name. Rocket writes a print line for launch 0, then launch 1, then launch 2.
"Tomorrow there will be five launches," Raven says. "What do you notice? Every print line is the same except the index."
Rocket groans, then laughs. "A loop! Of course." Nova draws an arrow that slides down the row of cards. "Would you like a hint? Each round, the loop variable holds one whole record."
A for loop over a list of dictionaries gives you one record each round.
Use a key to read a fact from that record.
launches = [
{"name": "Moon hop", "gate": 2, "time": "0900"},
{"name": "Ring tour", "gate": 7, "time": "1300"},
{"name": "Mars run", "gate": 4, "time": "1600"},
]
for launch in launches:
print(launch["time"], launch["name"], "at gate", launch["gate"]) | The screen shows |
|---|
| 0900 Moon hop at gate 2 |
| 1300 Ring tour at gate 7 |
| 1600 Mars run at gate 4 |
crew = [
{"name": "Rocket", "job": "builder", "shifts": 3},
{"name": "Raven", "job": "explorer", "shifts": 4},
{"name": "Kai", "job": "pilot", "shifts": 2},
]
total = 0
for person in crew:
print(person["name"], "is the", person["job"])
total = total + person["shifts"]
print("Shifts:", total) | Inside the crew loop above | True or false? |
|---|---|
| person holds one dictionary each round. | ? |
| person["job"] reads the job from that record. | ? |
| person[0] gives the name. | ? |
pods = [
{"id": "A", "crew": 3},
{"id": "B", "crew": 5},
{"id": "C", "crew": 2},
]
big = 0
for p in pods:
print("Pod", p["id"], "has", p["crew"])
if p["crew"] > 2:
big = big + 1
print("Big pods:", big) | Statement | True or false? |
|---|---|
| The loop runs once for each record. | ? |
| p["id"] reads the id of the current record. | ? |
| Big pods: prints once for each record. | ? |
| A loop can count the records that match a rule. | ? |
Nice work! Tomorrow you will pick out only the records you need.