Crew members send in requests: tape, rope and water. Rocket's program looks up each one. On rope, Python stops with a KeyError. "We have never had rope!" Rocket says.
Raven reads the error. "What do you notice? The program asked for a key that is not there."
Nova shines a small light into the empty corner of the shelf. "Would you like a hint? You used a word a few weeks ago to check if a string was inside another. It works on dictionaries too."
key in dictionary gives True if the key is there, and False if it is not.
Check with in first. Then you never look up a missing key.
inventory = {"water": 12, "oats": 8, "tape": 3}
requests = ["tape", "rope", "water"]
for r in requests:
if r in inventory:
print(r, "on board:", inventory[r])
else:
print(r, "not on board") | The screen shows |
|---|
| tape on board: 3 |
| rope not on board |
| water on board: 12 |
| inventory = {"water": 12, "oats": 8} | Does Python say True? |
|---|---|
| "oats" in inventory | ? |
| "rope" in inventory | ? |
| 12 in inventory | ? |
| "Water" in inventory | ? |
inventory = {"water": 12, "tape": 1}
requests = ["tape", "tape", "water"]
for r in requests:
if inventory[r] > 0:
inventory[r] = inventory[r] - 1
print("Gave", r)
else:
print("Out of", r)
print(inventory) and is True only when both sides are True. Python checks the left side first, so a missing key is never looked up.
stock = {"tape": 2, "glue": 0}
asks = ["glue", "tape", "rope"]
for a in asks:
if a in stock and stock[a] > 0:
print("Yes:", a)
else:
print("No:", a) | Statement | True or false? |
|---|---|
| in checks the keys, not the values. | ? |
| "rope" in stock is True. | ? |
| and is True when only one side is True. | ? |
| Checking with in first prevents a KeyError. | ? |
Week seven is done! You can look up, change, add and check keys. Next week, you will choose between lists and dictionaries.