← Back to course
Code Crew G4 / Week 07 / Crew Quest
6/6
Week 07 Β· Dictionaries

Crew Quest

Crew Quest: Labeled Jars
// Look it up by name
⏱ about 15 min

Crew Quest: Labeled Jars

Raven sets out five cups in the galley. She writes a label on a sticky note for each one: water, oats, tape, lamps, rope. Inside each cup, she drops some paper clips.

"This is a dictionary," she says. "What do you notice? The label is the key, and the clips are the value."

Rocket grabs the tape cup and counts. "Three!" Nova chirps happily. "You just looked up a key. Now try changing a value."

  1. A dictionary stores key: value pairs inside curly braces.
  2. inventory["oats"] looks up a value by its key.
  3. inventory["oats"] = 5 changes a value, or adds a new pair if the key is new.
  4. A for loop over a dictionary visits each key.
  5. key in inventory checks if a key is there before you look it up.
β—‡ LABELED JARS
Set out four cups. Label each one with a sticky note.
Put some small objects in each cup, like paper clips or buttons.
Your partner says a line, like cups["tape"] = cups["tape"] + 2.
Do it with real objects. Then say the new value.
Try a key with no cup. Shout KeyError!
cups = {"tape": 3, "rope": 5}
cups["tape"] = cups["tape"] + 2
cups["lamps"] = 1
total = 0
for c in cups:
    total = total + cups[c]
print(total)
What number does the jar program show?
WHY THIS EXERCISEThis checks changing, adding and looping all together.
BONUS RECAP
  • Read the question.
  • Tap your answer.
d = {"a": 2}. What does d["a"] give?
d["new"] = 1 runs, and "new" is not a key yet. What happens?
In for k in d:, what is k?

Wonderful week! Next week, you will mix lists and dictionaries together.

← Friday