← Back to course
Code Crew G5 / Week 01 / Thursday
4/6
Week 01 Β· Crew check

Thursday

Dictionaries
// The tools you already have
⏱ about 15 min

Thursday: Dictionaries

Every ship in the fleet carries supplies. Rocket keeps the counts in a long list of numbers.

"How many seeds do we have?" Raven asks. Rocket scrolls. "Um, is it the second number or the third?"

Raven smiles. "What do you notice? The numbers have no labels."

Rocket groans. "So I cannot tell which number is which."

Nova circles the screen. "Here is a hint. A dictionary keeps a label next to every value."

Keys and values

A dictionary pairs each key with a value. Curly brackets wrap it. A colon sits between each key and its value.

You look up a value with its key in square brackets. You can change a value, or add a new key, the same way.

cargo = {"water": 12, "seeds": 5, "maps": 3}
print(cargo["seeds"])
cargo["maps"] = 4
cargo["lamps"] = 2
print(cargo)
print(len(cargo))
Output:
5
{'water': 12, 'seeds': 5, 'maps': 4, 'lamps': 2}
4
  • cargo["seeds"] looks up the value for the key "seeds".
  • cargo["maps"] = 4 changes a value that was already there.
  • cargo["lamps"] = 2 adds a brand new key.
  • len(cargo) counts the keys.
What does print(cargo["water"]) show?
Then cargo["water"] = cargo["water"] - 2 runs. What is cargo["water"] now?

Is the key there?

The word in checks whether a key is in the dictionary. It gives True or False.

cargo = {"water": 12, "seeds": 5}
print("seeds" in cargo)
print("tea" in cargo)
for item in cargo:
    print(item, cargo[item])
PREDICT THE OUTPUT OF THE PROGRAM ABOVE.
  • Read the question.
  • Tap your answer.
What does print("tea" in cargo) show?
What is the last line the loop prints?
StatementTrue or false?
A dictionary looks up values by key.?
A dictionary key must be a number.?
Setting a new key adds it to the dictionary.?
WHY THIS EXERCISEKeys can be words, so a dictionary reads like a labeled catalog.

Practice lab: the fleet dictionary

fleet = {"scouts": 4, "haulers": 2}
fleet["haulers"] = fleet["haulers"] + 3
fleet["medics"] = 1
total = 0
for kind in fleet:
    total = total + fleet[kind]
print(fleet)
print(total)
What is fleet["haulers"] at the end?
What is len(fleet) at the end?
What does the last line show?
KEY CHECK
  • Read the question.
  • Tap your answer.
What does "medics" in fleet give?
What does 1 in fleet give?
What does the loop variable kind hold?
StatementTrue or false?
Setting a new key adds a pair.?
fleet["pilots"] gives 0 when the key is missing.?
Keys can be strings.?
The loop visits the keys in the order they were added.?
WHY THIS EXERCISEA missing key gives a KeyError, not 0. Check with in first.
What does fleet["scouts"] * fleet["medics"] give?
WHY THIS EXERCISE4 times 1 is 4.

Great work! Labels make data easy to find. Tomorrow we review functions that hand back a value with return.

← Wednesday