Some launches are ready, and some are on hold for repairs. The pilots only want to see the ready ones. Rocket prints every launch, then crosses out the held ones by hand.
"That is a lot of crossing out," Raven says. "What do you notice? Each record already has a status."
Nova makes the held cards fade to gray. "Would you like a hint? You have used a loop with an if before. It works on records too."
To filter is to keep only the items that match a rule.
Loop through the records. Use an if to check a key. Append the ones that match.
launches = [
{"name": "Moon hop", "status": "ready"},
{"name": "Ring tour", "status": "hold"},
{"name": "Mars run", "status": "ready"},
{"name": "Comet chase", "status": "hold"},
]
ready = []
for launch in launches:
if launch["status"] == "ready":
ready.append(launch["name"])
print("Ready:", ", ".join(ready))
print(len(ready), "of", len(launches)) | The screen shows |
|---|
| Ready: Moon hop, Mars run |
| 2 of 4 |
trips = [
{"pilot": "Kai", "fuel": 30},
{"pilot": "Raven", "fuel": 55},
{"pilot": "Rocket", "fuel": 48},
]
for t in trips:
if t["fuel"] > 40:
print(t["pilot"], "needs a big tank") items = [
{"name": "tape", "count": 1},
{"name": "rope", "count": 6},
{"name": "glue", "count": 0},
{"name": "lamp", "count": 4},
]
low = []
for i in items:
if i["count"] < 2:
low.append(i["name"])
print(low)
print(len(low)) | Statement | True or false? |
|---|---|
| The low list holds names, not whole records. | ? |
| rope is in the low list. | ? |
| The loop checks every record. | ? |
| glue is low because its count is 0. | ? |
You can filter records! Tomorrow you will decide which container fits each job.