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

Monday

Keys and values
// Look it up by name
⏱ about 15 min

Monday: Keys and values

Rocket keeps the cargo in two lists. One list has names: water, oats, tape. The other list has counts: 12, 8, 3. Raven asks, "How much tape do we have?"

Rocket finds tape at index 2 in the first list. Then he counts to index 2 in the second list. "Three! I think."

"What do you notice?" Raven asks. "You have to match up two lists every time." Nova projects a row of jars, each with a label. "Would you like a hint? What if every number wore its own name tag?"

A dictionary stores pairs

A dictionary stores pairs. Each pair has a key and a value, with a colon between them.

Curly braces { } hold the dictionary. Commas go between the pairs.

To look up a value, put its key in square brackets.

inventory = {"water": 12, "oats": 8, "tape": 3}
print(inventory["oats"])
print(inventory)
The screen shows
8
{'water': 12, 'oats': 8, 'tape': 3}
KeyValue
"water"12
"oats"8
"tape"3
  • A list uses index numbers. A dictionary uses keys.
  • Each key appears only once in a dictionary.
  • Looking up a key that is not there stops Python with a KeyError.
What does print(inventory["water"]) show?
WHY THIS EXERCISELooking up by key is faster and clearer than matching two lists.
gates = {"Mars run": 4, "Moon hop": 2, "Ring tour": 7}
print(gates["Ring tour"])
LOOK IT UP
  • Read the question.
  • Tap your answer.
What does the program above show?
Which line shows the gate for the Moon hop?
Statement about dictionariesTrue or false?
A dictionary uses curly braces.?
A colon goes between a key and its value.?
inventory[0] gives the first value.?
Looking up a missing key gives a KeyError.?
WHY THIS EXERCISEKnowing these rules helps you read any dictionary.
Try it
Make a dictionary of three things in your kitchen and how many there are.
Write it with curly braces and colons.

Practice lab: the ship log

ships = {"Comet": 6, "Arrow": 4, "Drift": 9}
print(ships["Drift"])
print(ships["Comet"] + ships["Arrow"])
print(len(ships))
What does line 2 show?
What does line 3 show?
What does line 4 show?
PAIRS CHECK
  • Read the question.
  • Tap your answer.
In "Comet": 6, which part is the key?
What goes between the pairs?
What happens with print(ships["Zoom"])?
StatementTrue or false?
{"a": 1, "b": 2} has 2 pairs.?
Square brackets wrap a dictionary.?
A key can appear twice in one dictionary.?
ships["Arrow"] gives 4.?
WHY THIS EXERCISECurly braces, one copy of each key, and lookups by key.
tools = {"drill": 2, "clamp": 5}. What does print(tools["clamp"]) show?
WHY THIS EXERCISEThe key leads straight to its value. No counting needed.

Great start! Tomorrow you will change the values in a dictionary.