Nested Data · Examples
Beginner

Nested Data Examples

Short, runnable programs that show python nested data structures in action. Read the explanation, press Run, then change the code and try your own ideas. New to the topic? Start with the Python Nested Data Structures lesson.

1Average score per student (dict of lists)

Each key holds a list of marks. .items() hands you the name and the list together, and max() with a key= finds the best student without sorting everything.

Average score per student (dict of lists)
scores = {"Asha": [82, 90, 75], "Ben": [67, 71], "Cara": [95, 88, 91, 79]}
averages = {}
for name, marks in scores.items():
    averages[name] = round(sum(marks) / len(marks), 1)
print(averages)
best = max(averages, key=averages.get)
print("Best:", best, averages[best])
Expected output{'Asha': 82.3, 'Ben': 69.0, 'Cara': 88.2}
Best: Cara 88.2

2Group records into a dict of lists

setdefault() makes the inner list the first time a city appears. Afterwards the same line just appends to it.

Group records into a dict of lists
people = [
    {"name": "Asha", "city": "Pune"},
    {"name": "Ben", "city": "Delhi"},
    {"name": "Cara", "city": "Pune"},
    {"name": "Dev", "city": "Goa"},
]
by_city = {}
for person in people:
    by_city.setdefault(person["city"], []).append(person["name"])
print(by_city)
print(len(by_city["Pune"]), "people in Pune")
Expected output{'Pune': ['Asha', 'Cara'], 'Delhi': ['Ben'], 'Goa': ['Dev']}
2 people in Pune

3Filter and sort a list of dicts

A comprehension keeps the products inside the budget, and sorted() with a key= function puts the cheapest first. Neither step changes the original products list.

Filter and sort a list of dicts
products = [
    {"name": "Desk", "price": 120, "stock": 3},
    {"name": "Lamp", "price": 35, "stock": 0},
    {"name": "Chair", "price": 80, "stock": 7},
    {"name": "Mug", "price": 8, "stock": 40},
]
budget = 100
affordable = [p for p in products if p["price"] <= budget and p["stock"] > 0]
for p in sorted(affordable, key=lambda p: p["price"]):
    print(p["name"], p["price"])
print(len(products), "products in the catalogue")
Expected outputMug 8
Chair 80
4 products in the catalogue

4Column totals by transposing a grid

zip(*grid) turns rows into columns, so summing each column gives the total per weekday. The header row is kept separate so it is not added.

Column totals by transposing a grid
days = ["Mon", "Tue", "Wed"]
sales = [
    [12, 9, 15],   # north
    [7, 14, 10],   # south
    [5, 6, 8],     # east
]
for day, column in zip(days, zip(*sales)):
    print(day, column, sum(column))
print([sum(row) for row in sales])
Expected outputMon (12, 7, 5) 24
Tue (9, 14, 6) 29
Wed (15, 10, 8) 33
[36, 31, 19]

5Reading incomplete records safely

Some users have no contact data and some have an empty one. (user.get("contact") or {}) covers both, and .get() with a default fills the gaps in the printed report.

Reading incomplete records safely
users = [
    {"name": "Asha", "contact": {"email": "asha@example.com", "phone": "555-0101"}},
    {"name": "Ben", "contact": {"email": "ben@example.com"}},
    {"name": "Cara"},
    {"name": "Dev", "contact": None},
]
for user in users:
    contact = user.get("contact") or {}
    print(user["name"], contact.get("email", "no email"), contact.get("phone", "-"))
Expected outputAsha asha@example.com 555-0101
Ben ben@example.com -
Cara no email -
Dev no email -

6Update a dict of dicts in place

The inventory is a lookup table keyed by SKU. Restocking changes a value two layers down, and adding a new SKU creates a new inner dict. Printing the whole structure with json.dumps(..., indent=2) makes nesting easy to see.

Update a dict of dicts in place
import json

inventory = {
    "A1": {"name": "pen", "qty": 10},
    "B7": {"name": "lamp", "qty": 2},
}
inventory["B7"]["qty"] += 5
inventory["C3"] = {"name": "mug", "qty": 12}
low_stock = [sku for sku, item in inventory.items() if item["qty"] < 8]
print(low_stock)
print(json.dumps(inventory, indent=2))
Expected output['B7']
{
  "A1": {
    "name": "pen",
    "qty": 10
  },
  "B7": {
    "name": "lamp",
    "qty": 7
  },
  "C3": {
    "name": "mug",
    "qty": 12
  }
}

Practise next

Python Nested Data Structures exercises → Back to the lesson

Python Lists examplesPython Dictionaries examplesCopying Lists and Dicts examplesWorking with JSON in Python examples