← Back to course
Code Crew G4 / Week 07 / Tuesday
2/6
Week 07 Β· Dictionaries

Tuesday

Change a value
// Look it up by name
⏱ about 15 min

Tuesday: Change a value

The crew used two bottles of water at lunch. Then the supply ship dropped off more tape, and now there are seven rolls. "Let's update the inventory!" Rocket says.

He starts typing a whole new dictionary from the top. Raven stops him. "What do you notice? Only two numbers changed. The oats are the same."

Nova taps one glowing jar with her wing. "Would you like a hint? You can change just one value if you know its key."

Store a new value by key

Put the dictionary name and the key on the left of =. Put the new value on the right.

You can use the old value too, just like fuel = fuel + 15.

inventory = {"water": 12, "oats": 8, "tape": 3}
inventory["water"] = inventory["water"] - 2
inventory["tape"] = 7
print(inventory["water"])
print(inventory["tape"])
print(inventory["oats"])
The screen shows
10
7
8
Linewateroatstape
11283
21083
31087
fuel = {"shuttle": 40, "rover": 15}
fuel["shuttle"] = fuel["shuttle"] + 25
fuel["rover"] = fuel["rover"] * 2
print(fuel)
shuttle at the end
rover at the end
WHICH LINE?
  • Read the question.
  • Tap your answer.
The crew opens 3 bags of oats. Which line updates the inventory?
scores = {"Rocket": 5, "Raven": 5}
scores["Rocket"] = scores["Rocket"] + 3
scores["Raven"] = scores["Rocket"]
print(scores["Raven"])
What number does the program above show?
WHY THIS EXERCISETrace one line at a time. The order of the lines matters.
Try it
Use your kitchen dictionary from Monday.
Pretend you used one thing. Write the line that updates it.

Practice lab: trace the air

air = {"deck1": 90, "deck2": 75}
air["deck1"] = air["deck1"] - 10
air["deck2"] = air["deck2"] + 5
air["deck1"] = air["deck1"] - 10
print(air)
deck1 after line 2
deck2 after line 3
deck1 at the end
UPDATE CHECK
  • Read the question.
  • Tap your answer.
Which line adds 4 to the rover value?
d = {"x": 2}. Then d["x"] = d["x"] * 3 runs. What is d["x"]?
Does changing one key change the other values?
StatementTrue or false?
inventory["oats"] = 9 changes the oats value.?
You must retype the whole dictionary to change one value.?
The right side of = is worked out first.?
After d["a"] = 1 and then d["a"] = 2, d["a"] is 1.?
WHY THIS EXERCISEA key holds one value at a time, just like a variable.
pods = {"A": 4}. Then pods["A"] = pods["A"] + pods["A"] runs. What is pods["A"]?
WHY THIS EXERCISE4 plus 4 is 8, and that new value is stored back by key.

Nice updating! Tomorrow you will add brand new keys.

← Monday