Changing
Python · Unit 7: Dictionaries
- Full plan
- Python
- 10 exercises
To add a pair, assign to a new key: d[key] = value. If the key already exists, the same line changes its value.
That's why a dictionary never has two equal keys.
stock = {"bun": 4}
stock["milk"] = 2
stock["bun"] = 10
print(stock)Prints
{'bun': 10, 'milk': 2}The rest of the explanation is in the lesson, which is part of the full plan.
Exercises in this lesson
You do them in the app, which checks them on the spot and explains why.
1. Predict the output
What does this code print?
2. Find the bug
This program should add Jake with an 8 and show all the grades. Which line has the bug?
3. Complete the code
Rice went up. Complete it so it costs 5 more than before.
4. Predict the output
What does this code print?
5. Multiple choice
What's the difference between
del d["bun"]andd.pop("bun")?6. Predict the output
What does this code print?
7. Complete the code
Complete it to remove the bun only if it's in the cart.
8. Put the lines in order
Put in order the function that adds an item to the cart. If it was already there, it gets one more; if not, it goes in with 1.
9. Find the case that fails
remove(cart, item)should take the item out and return the cart. If the item isn't there, it returns the cart unchanged. Which call does it fail with?10. Predict the output
This is how you count votes. What does it print?
It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.