python · level 2 · unit 1 · lesson 2
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Dictionaries are : add, replace and remove pairs.
A dictionary is mutable, which means you can change it after you make it. Store a value under a new key and a pair is added. Store a value under a key that already exists and its old value is replaced.
removes the milk pair completely. len(basket) counts the pairs.
Before you look something up, you can ask first. "milk" in basket is True only when that key is there, and "milk" not in basket is the opposite.
basket = {"apples": 3, "milk": 1}
basket["bread"] = 1
basket["apples"] = 5
del basket["milk"]
print(basket)
print("milk" in basket)
print(len(basket)) in only checks the keys of a dictionary, never its values.
guess first
Ava scores again. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
scores = {"Ava": 7, "Ben": 5}
scores["Ava"] = 9
scores["Cara"] = 6
print(scores)
your turn
Your turn. Run the lost property desk.
Someone hands in a new item: add it in the first blank. The scarf has been collected: remove it in the second. In the last blank, check whether scarf is still there.
fix it
Zara is new, and the points card crashes. Fix it!
- Read the error: a KeyError for Zara. Line 4 was meant to give her a starting score.
- Line 4 compares with
==instead of storing with=, so nothing is ever stored. - Change == to = on line 4, then run.
nailed it
your dictionaries can change now. :D
- Store under a new key to add a pair.
- Store under an existing key to replace its value.
delremoves a pair, andinchecks for a key.
new words in your collection
- mutable
- del
This lesson isn’t saved. A free account remembers every lesson you finish.