← Back to course
Code Crew G6+ / Week 05 / Crew Quest
6/6
Week 05 Β· Lists and dictionaries

Crew Quest

Crew Quest: Supply inventory
// Keeping many values together
⏱ about 30 min

Saturday: Crew Quest: Supply inventory

The supply closet at Mission Control is a mystery. Nobody knows how many flashlights are left, and the clipboard list on the door is covered in crossed-out numbers.

"A dictionary," Rocket says right away. "Item names as keys, amounts as values. We update it as things come and go."

Raven opens the closet and starts counting. "What do you notice?" she asks. "Some items come in, some go out. The program needs to add and take away."

Nova scans the shelves with a soft beam. "Interesting," she says. "If someone takes an item that is not on the list, what should happen? Decide before you code."

Rocket writes the question in his notebook and circles it.

  1. A list keeps items in order. Index 0 is first and index -1 is last.
  2. append, pop and sort change a list. in checks whether an item is there.
  3. for item in a_list visits each item. enumerate adds a counter.
  4. A dictionary stores values under keys. get() gives a default when a key is missing.
  5. counts[key] = counts.get(key, 0) + 1 counts anything.
# inventory.py
stock = {"flashlight": 4, "rope": 2, "tape": 6}
stock["rope"] = stock["rope"] - 1
stock["batteries"] = stock.get("batteries", 0) + 8
for item, amount in stock.items():
    print(f"{item}: {amount}")
flashlight: 4
rope: 1
tape: 6
batteries: 8
β—‡ COUNT A REAL SHELF
With a grown-up, pick a shelf or drawer at home with a few kinds of things, like pencils, books or socks.
Count each kind and write a dictionary on paper, like {"pencils": 7, "erasers": 2}.
Type it into inventory.py instead of the supply closet. Add a line for something you use up and one for something you add.
Ask your grown-up to change a number and predict the new output.
WEEK 5 CHECK
  • Read the question.
  • Tap your answer.
stock = {"rope": 2}. What does stock.get("tape", 0) give?
nums = [4, 1, 3]. What is nums after nums.append(2) and nums.sort()?
MORE REVIEW: WEEK 5
  • Read the question.
  • Tap your answer.
planets = ["Mars", "Venus", "Earth"]. What is planets[-1]?
probe = {"battery": 87}. What does probe.get("speed", 0) give?
Which method adds an item to the end of a list?

Excellent work. Next week you will package your code into functions and modules.

← Friday