A crate of lamps arrives from the supply ship. Lamps are not in the inventory yet. "We need a new jar," Rocket says. "Let's build it!"
He looks for a special add command, like append for lists. Raven smiles. "What do you notice about the line we use to change a value? What if the key is new?"
Nova sets an empty glowing jar on the shelf. "Would you like a hint? The same kind of line can change a value or make a new pair."
If the key is already there, the line changes its value.
If the key is new, the line adds a new pair to the dictionary.
len counts the pairs in a dictionary.
inventory = {"water": 12, "oats": 8}
inventory["lamps"] = 4
inventory["water"] = 20
print(inventory)
print(len(inventory)) | The screen shows |
|---|
| {'water': 20, 'oats': 8, 'lamps': 4} |
| 3 |
| inventory = {"water": 12, "oats": 8}. Then this line runs: | Does it add a new pair? |
|---|---|
| inventory["tape"] = 5 | ? |
| inventory["oats"] = 9 | ? |
| inventory["rope"] = 1 | ? |
| inventory["water"] = 0 | ? |
crew_jobs = {}
crew_jobs["Rocket"] = "builder"
crew_jobs["Raven"] = "explorer"
crew_jobs["Kai"] = "pilot"
crew_jobs["Rocket"] = "engineer"
print(len(crew_jobs))
print(crew_jobs["Rocket"]) log = {}
log["mon"] = 3
log["tue"] = 5
log["mon"] = log["mon"] + 1
log["wed"] = 2
print(log)
print(len(log)) | Statement | True or false? |
|---|---|
| A new key makes a new pair. | ? |
| A key that is already there gets a second pair. | ? |
| len counts the pairs. | ? |
| Dictionaries use append to add pairs. | ? |
You can add to a dictionary now. Tomorrow you will loop through every key.