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

Thursday

Dictionaries
// Keeping many values together
⏱ about 30 min

Thursday: Dictionaries

Probe 7 sends home a status report with its name, its battery level and its job. Rocket stores it as a list, but a week later he cannot remember whether the battery was item 1 or item 2.

"I keep guessing numbers," he says. "Was battery at index 1? Or was that the status?"

Raven opens her field guide to a page of labeled boxes. "What do you notice?" she asks. "In my guide, I look things up by name, not by page position."

Nova displays a glowing card with labels down the left side. "Would you like a hint?" she asks. "Python has a type that stores values under names. The names are called keys."

Rocket rewrites the report so every value has a label.

Keys and values

A dictionary is written with curly brackets. Each entry is a key, a colon and a value, with commas between entries. You look up a value with its key in square brackets.

To change a value, or add a new key, store a value with that key. Keys are often strings.

# probe.py
probe = {"name": "Probe 7", "battery": 87, "status": "active"}
print(probe["name"])
probe["battery"] = 80
probe["zone"] = "north"
print(probe)
print(probe.get("speed"))
print(probe.get("speed", 0))
print("zone" in probe)
Probe 7
{'name': 'Probe 7', 'battery': 80, 'status': 'active', 'zone': 'north'}
None
0
True

get() and KeyError

Looking up a key that is not there with square brackets gives a KeyError, and the program stops. The get() method is gentler: it gives None, or a default you choose, when the key is missing.

None is a special Python value that means nothing here.

>>> probe = {"name": "Probe 7", "battery": 87}
>>> probe["speed"]
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
KeyError: 'speed'
ship = {"crew": 4, "fuel": 90}. What is ship["fuel"]?
What does ship.get("cargo", 0) give?
After ship["crew"] = 5, what is ship["crew"]?
LIST OR DICTIONARY?
  • Read the question.
  • Tap your answer.
You want the planets in order from the Sun. Which fits best?
You want to look up a probe's battery by the word battery. Which fits best?
At your computer
1. Type probe.py, save it and run it.
2. Add a line that changes status to "sleeping" and prints the dictionary again.
3. In the shell, make probe = {"name": "Probe 7"} and type probe["speed"]. Read the KeyError.
4. Now type probe.get("speed", "unknown") and press Enter.

Practice: looping over keys

A for loop over a dictionary gives you its keys, one at a time, in the order they were added. The len() function counts the keys.

# rover.py
rover = {"name": "Rover 2", "wheels": 6, "speed": 4}
rover["speed"] = rover["speed"] + 1
rover["color"] = "white"
print(rover["speed"])
print(len(rover))
for key in rover:
    print(key)
5
4
name
wheels
speed
color
READ ROVER.PY
  • Read the question.
  • Tap your answer.
Why does the first print show 5?
Why does len(rover) show 4?
What does for key in rover give each time round?
What is rover["wheels"]?
What does rover.get("lights", "none") give?
What does "speed" in rover give?
StatementTrue or false?
A dictionary key is used to look up its value.?
Storing a value under a new key adds it to the dictionary.?
rover["fuel"] gives None when there is no fuel key.?
Keys in a dictionary are found by index number.?
WHY THIS EXERCISEA missing key in square brackets gives a KeyError, and dictionaries use keys, not positions.

Dictionaries give every value a clear label. Tomorrow you will loop through dictionaries and combine them with lists.

← Wednesday