A small inventory
Change a stock number and see how the total and the out-of-stock list change. The first line, import pprint, loads the pretty-printing module (Topic 6.1 teaches import).
Real data is nested: a list of dictionaries whose values are lists or more dictionaries. This topic shows how to read, search, update and print such JSON-shaped data safely, which is the shape of every web API and AI model response.
Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.
Ready for more? This phase has 6 hands-on exercises with automatic checks.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Given students = [{"name": "Asha", "marks": [80, 90]}, {"name": "Ravi", "marks": [70, 60, 65]}], print each student's name and average mark.
From the same data, build a dictionary mapping each name to the highest mark.
Given config = {"db": {"host": "localhost"}}, print the port with a default of 5432 without raising an error.
Explain it without notes
How do you read the second tag of the first item in a list of dictionaries?
How do you safely read a value that may be missing, several levels deep?
How does JSON map onto Python types?
Why can changing found["stock"] change the list?
Expected output
stock value: 4500
out of stock: ['notebook']
by tag: {'stationery': ['pen', 'notebook'], 'blue': ['pen'], 'sale': ['notebook'], 'school': ['bag']}
{'name': 'bag', 'price': 500, 'stock': 6, 'tags': ['school']}