← Back to course
Code Crew G4 / Week 08 / Wednesday
3/6
Week 08 Β· List or dictionary?

Wednesday

Pick the records you need
// Records and the right container
⏱ about 15 min

Wednesday: Pick the records you need

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."

Filter with an if

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
Change "ready" to "hold" in the if. What is the first name after Ready:?
What does the second line show then? Type the first number.
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")
How many lines does the program above show?
WHY THIS EXERCISEFiltering with numbers works just like filtering with strings.
WRITE THE RULE
  • Read the question.
  • Tap your answer.
Which if keeps only launches at gate 4?
Try it
Lay out the record cards you made on Monday.
Pick a rule and filter them by hand.

Practice lab: find the low items

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))
How many items are low?
Which item name goes into low first?
If the rule were < 5, how many would be low?
FILTER CHECK
  • Read the question.
  • Tap your answer.
What does it mean to filter?
Which list starts empty before the loop?
Which if keeps items with a count over 3?
StatementTrue 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.?
WHY THIS EXERCISEYou choose what to keep: a name, a number or the whole record.
Change the rule to i["count"] == 0. How many names are in low now?
WHY THIS EXERCISEOnly glue has a count of 0.

You can filter records! Tomorrow you will decide which container fits each job.

← Tuesday