Nested Data · Exercises
Beginner

Nested Data Exercises

4 exercises that build on the Python Nested Data Structures lesson, from easy to hard. Each one is checked in your browser when you press Check. Stuck? Use the hint before peeking at the solution.

What this lesson covers: A nested data structure is a list, dict or tuple that contains other lists or dicts, and you reach a value deep inside by writing one key or index for each level, from the outside in. By the end you can read and change values inside lists of dicts, dicts of lists and grids, loop over records, filter, sort and total them, read optional fields safely, and fix KeyError, IndexError and TypeError caused by using the wrong depth. You will practise: Dig into an order; Predict the grid; Fix the category totals; Find the top spenders.

0 / 4 completed

Nested Data practice exercises

1. Dig into an order

Write code Easy

The dict order is given. Create three variables:

  • city: the customer's city
  • last_name: the "name" of the last item in order["items"] (it should still work if more items are added)
  • total_qty: the sum of the "qty" of all items

Then print city.

Your code
order = {
    "id": 1042,
    "customer": {"name": "Ben", "city": "Pune"},
    "items": [
        {"name": "pen", "qty": 4},
        {"name": "notebook", "qty": 2},
        {"name": "stapler", "qty": 1},
    ],
}

# your code here

2. Predict the grid

Predict the output Medium

Read the code and type exactly what it prints. Pay attention to when cols is created and what zip(*grid) produces.

Read this code
grid = [[1, 2, 3], [4, 5, 6]]
cols = [list(col) for col in zip(*grid)]
print(cols)
print(grid[1][-1], cols[2][0])
grid[0][0] = 99
print(sum(row[0] for row in grid))
print(cols[0])

3. Fix the category totals

Fix the bug Medium

spend_by_category(expenses) should return a dict that adds up the "amount" of every expense per "category", so the program should print {'food': 20, 'travel': 40}. Instead it crashes with a KeyError. Fix the function.

Your code
def spend_by_category(expenses):
    totals = {}
    for expense in expenses:
        category = expense["category"]
        totals[category] += expense["amount"]
    return totals

expenses = [
    {"category": "food", "amount": 12},
    {"category": "travel", "amount": 40},
    {"category": "food", "amount": 8},
]
print(spend_by_category(expenses))

4. Find the top spenders

Write code Hard

Each order in the list orders is a dict like {"id": 1, "customer": {"name": "Asha", "city": "Pune"}, "items": [{"name": "pen", "price": 2.5, "qty": 4}]}.

Write top_spenders(orders, min_total) that returns a list of (name, total) tuples, one per customer:

  • total is the sum of price * qty over all items of all orders placed by that customer name, rounded to 2 decimals
  • keep only customers whose rounded total is at least min_total
  • sort by total, highest first; customers with equal totals are sorted by name

Print top_spenders(orders, 25) at the end.

Your code
def top_spenders(orders, min_total):
    # return a list of (name, total) tuples, highest total first
    pass

orders = [
    {"id": 1, "customer": {"name": "Asha", "city": "Pune"},
     "items": [{"name": "pen", "price": 2.5, "qty": 4}, {"name": "book", "price": 10, "qty": 1}]},
    {"id": 2, "customer": {"name": "Ben", "city": "Delhi"},
     "items": [{"name": "lamp", "price": 30, "qty": 1}]},
    {"id": 3, "customer": {"name": "Asha", "city": "Pune"},
     "items": [{"name": "bag", "price": 15.5, "qty": 2}]},
]
print(top_spenders(orders, 25))

Next lessonCopying Lists and Dicts

More Python Nested Data Structures examples · All Python exercises