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."
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 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]) | Statement | True 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. | ? |
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) | Statement | True 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. | ? |
Great work! Labels make data easy to find. Tomorrow we review functions that hand back a value with return.