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.
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 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' 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
| Statement | True 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. | ? |
Dictionaries give every value a clear label. Tomorrow you will loop through dictionaries and combine them with lists.