Rocket starts typing the supplies as a list: 40, 12, 3, 7. Then he frowns.
"Wait. Which number was lamps again?" he asks.
Raven smiles. "What do you notice? This happened in week 1."
"The numbers need labels!" Rocket laughs. "A dictionary!"
Nova twirls. "Here is a hint. Ask what each piece of data must do, then pick the container that does it best."
| Data | Container | Why |
|---|---|---|
| Supplies and their counts | dictionary | look up a count by the supply name |
| Names to search fast | sorted list | binary search needs a sorted list |
| The command tree | nested dictionaries | each person has a name and a list of crew |
inventory = {"water": 40, "seeds": 12, "lamps": 3}
names = sorted(inventory)
print(names)
print(inventory["lamps"]) Output: ['lamps', 'seeds', 'water'] 3
sorted() on a dictionary gives a sorted list of its keys. That is how the tracker gets a list to binary search.
| Statement | True or false? |
|---|---|
| A plain list of numbers is a good way to store named supplies. | ? |
| sorted(inventory) changes the inventory dictionary. | ? |
| A tree can be built from dictionaries and lists. | ? |
stock = {"rope": 2, "maps": 7, "water": 40, "fuel": 5}
print(sorted(stock))
print(stock["maps"])
print(len(stock))
stock["rope"] = stock["rope"] + 10
print(stock["rope"]) | Statement | True or false? |
|---|---|
| The sorted names can be used with binary search. | ? |
| len(stock) adds up all the counts. | ? |
| stock["water"] is 40. | ? |
| A dictionary keeps a label with each number. | ? |
Great choices! Good data makes good code. Tomorrow we write the tests before we write the code.