← Back to course
Code Crew G4 / Week 07 / Wednesday
3/6
Week 07 Β· Dictionaries

Wednesday

Add new pairs
// Look it up by name
⏱ about 15 min

Wednesday: Add new pairs

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."

New key? 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?
WHY THIS EXERCISEOne kind of line does two jobs. The key decides which.
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"])
First line on the screen
Second line on the screen
PUT THE LINES IN ORDER SO THE SCREEN SHOWS 2
  • ?pods = {}
  • ?pods["A"] = 6
  • ?pods["B"] = 9
  • ?print(len(pods))
WHY THIS EXERCISEA dictionary must exist before you can add to it.
Try it
Start an empty dictionary on paper.
Add three pairs about your day, like steps and a number.

Practice lab: build a log

log = {}
log["mon"] = 3
log["tue"] = 5
log["mon"] = log["mon"] + 1
log["wed"] = 2
print(log)
print(len(log))
What is log["mon"] at the end?
What does the last line show?
How many lines add a new pair?
ADD CHECK
  • Read the question.
  • Tap your answer.
What does { } make?
Which line adds a pair to an empty dictionary d?
d = {"a": 1}. Then d["b"] = 2 runs. What is len(d)?
StatementTrue 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.?
WHY THIS EXERCISEYou add a pair by storing a value with a new key.
d = { }. Then d["x"] = 1, d["y"] = 2 and d["x"] = 3 run. What is len(d)?
WHY THIS EXERCISEThe third line changes x. It does not add a new pair.

You can add to a dictionary now. Tomorrow you will loop through every key.

← Tuesday