← Back to course
Code Crew G5 / Week 11 / Wednesday
3/6
Week 11 Β· Plan your capstone

Wednesday

Pick the right data
// Choose, break it down, test it first
⏱ about 15 min

Wednesday: Pick the right data

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

Three containers

DataContainerWhy
Supplies and their countsdictionarylook up a count by the supply name
Names to search fastsorted listbinary search needs a sorted list
The command treenested dictionarieseach 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.

PICK THE CONTAINER.
  • Read the question.
  • Tap your answer.
You need the count of seeds by name.
You need to binary search for "maps".
You need to show who leads who.
inventory = {"water": 40, "rope": 2, "maps": 7}. What is sorted(inventory)[0]?
For the same inventory, what is len(inventory)?
StatementTrue 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.?
WHY THIS EXERCISEChoosing the right container makes every later function simpler.

Practice lab: work with stock

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"])
What is the first name in the sorted list?
What does print(stock["maps"]) show?
What does print(len(stock)) show?
What does the last line print?
CONTAINER CHECK
  • Read the question.
  • Tap your answer.
Tasks with names and times, to sort by time. Which container?
Which line does the job of restock?
Does sorted(stock) give the keys or the values?
StatementTrue 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.?
WHY THIS EXERCISEPicking the right container keeps each function short.
What is sorted(stock)[2]?
WHY THIS EXERCISESpot 2 is the third name in A to Z order.

Great choices! Good data makes good code. Tomorrow we write the tests before we write the code.

← Tuesday