Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 4.8 — Nested Data: Lists of Dicts and Friends
Python · Example 1 of 2

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.

01

Given students = [{"name": "Asha", "marks": [80, 90]}, {"name": "Ravi", "marks": [70, 60, 65]}], print each student's name and average mark.

02

From the same data, build a dictionary mapping each name to the highest mark.

03

Given config = {"db": {"host": "localhost"}}, print the port with a default of 5432 without raising an error.

Explain it without notes

01

How do you read the second tag of the first item in a list of dictionaries?

02

How do you safely read a value that may be missing, several levels deep?

03

How does JSON map onto Python types?

04

Why can changing found["stock"] change the list?

A small inventory
Sign in to run this example in your browser.

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']}