Lesson 9 of 10

Dictionaries and keys

Goal

Look up by key, not by position

01

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.

02

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
  1. The notebook is now 20 and the ruler was added with 7
  2. The pen and the eraser are unchanged
  3. bags is zero for an item that doesn't exist
  4. Asking about "bag" did not add it to stock
  5. available holds only the items with a quantity above zero, in order
03

Hints

0/3
Track lessons0 of 10 done

Start with the most beginner-friendly language there is, and use it to learn variables, strings, lists, conditions, loops and functions.

Beginner level, 10 lessons, 2 hours in total.

main.py
OutputPython (Pyodide)

Loading Python. This only happens once. Your browser keeps it after that.

–/5

Checks start once the environment is ready.

5 checks listed under “Your task”.

Track lessons0 of 10 done

Start with the most beginner-friendly language there is, and use it to learn variables, strings, lists, conditions, loops and functions.

Beginner level, 10 lessons, 2 hours in total.