The catalog is more than names now. Each star has a record with its name and its glow.
Rocket wants to know how brightly Halo glows. "My find function only works on a list of names," he sighs.
Raven points at one record. "What do you notice about each item in the list?"
"Each one is a dictionary," Rocket says. "So I check its name key."
Nova blinks. "Here is a hint. The search is the same. Only the thing you compare changes."
Each star is a dictionary. The loop looks at one dictionary at a time and checks its "name" key.
catalog = [
{"name": "Ember", "glow": 4},
{"name": "Frost", "glow": 9},
{"name": "Glow", "glow": 2},
{"name": "Halo", "glow": 7},
]
def glow_of(catalog, name):
for star in catalog:
if star["name"] == name:
return star["glow"]
return None
print(glow_of(catalog, "Halo"))
print(glow_of(catalog, "Pip")) Output: 7 None
A search does not have to look for an exact name. It can look for the first star that passes a test.
catalog = [
{"name": "Ember", "glow": 4},
{"name": "Frost", "glow": 9},
{"name": "Glow", "glow": 2},
{"name": "Halo", "glow": 7},
]
def first_bright(catalog, limit):
for star in catalog:
if star["glow"] > limit:
return star["name"]
return None
print(first_bright(catalog, 5)) Output: Frost
moons = [
{"name": "Ash", "size": 3},
{"name": "Bay", "size": 8},
{"name": "Cove", "size": 5},
]
def size_of(moons, name):
for moon in moons:
if moon["name"] == name:
return moon["size"]
return None
def first_small(moons, limit):
for moon in moons:
if moon["size"] < limit:
return moon["name"]
return None
print(size_of(moons, "Cove"))
print(first_small(moons, 4)) | Statement | True or false? |
|---|---|
| Each item in moons is a dictionary. | ? |
| size_of returns a name. | ? |
| first_small returns the first moon that passes the test. | ? |
| The program prints 5, then Ash. | ? |
Great work! Searching records is how real catalogs answer questions. Tomorrow we hunt a classic search bug.