Lesson 9 of 10
Dictionaries and keys
- 13 min
- 5 checks
- 3 hints
- Go to task
Goal
Look up by key, not by position
Explanation
A dictionary links each key to a value, like stock = {"pen": 12, "notebook": 5}, so you reach a value by its key rather than its position: stock["pen"]. You add a new value or change an existing one the same way: stock["ruler"] = 7. That's faster and clearer than searching a list every time you need a value.
update merges one dictionary into another in one go: it replaces the value of an existing key and adds any new key. items() gives you the key and the value together inside a loop: for item, qty in stock.items():.
Be aware that asking for a key that doesn't exist, like stock["bag"], raises a KeyError and stops the program. If the key might be missing, check first with "bag" in stock, or ask for it with stock.get("bag", 0), which returns the value if it exists and the default if it doesn't, without adding anything to the dictionary.
Your task
A new inventory count has come in, so update stock with update: the notebook quantity becomes 20 and a ruler is added with a quantity of 7. Then put the quantity of "bag" in bags using get with a default of 0, and set available to a list of the item names whose quantity is greater than zero, in dictionary order.
Checks
5 checks- The notebook is now 20 and the ruler was added with 7
- The pen and the eraser are unchanged
- bags is zero for an item that doesn't exist
- Asking about "bag" did not add it to stock
- available holds only the items with a quantity above zero, in order