Skip to contentSkip to navigation

Module 04 · Lesson 03

Nested Data Structures

Combine collections to model real data: grids as lists of lists, tables as lists of dictionaries, and groups as dictionaries of lists, read with chained indexes and safe lookups.

  • About 8 minutes
  • Builds on earlier lessons
  • 12-question quiz at the end

What you will learn

  • Grids of rows
  • Lists of records
  • Reach two levels deep
  • Watch X win

Collections inside collections

Put a list in a list, or a dictionary in a list, and you can describe almost anything.

  • Grids

    A list of rows: grid[1][2] is row 1, then column 2.

  • Records

    A list of dictionaries, one per person: pupils[0]["name"].

  • Groups

    A dictionary of lists: teams["red"] is a list of players.

  • Read outside in

    Each bracket goes one level deeper. Read them left to right.

Nested data everywhere

Real data is rarely flat. These are all collections inside collections.

  • Game mapsA level is a grid of tiles, one list per row.
  • Class listsEach pupil is a dictionary of name, form and scores, all inside one list.
  • Music librariesEach artist maps to a list of albums, and each album to a list of songs.
  • Weather appsForecasts arrive as nested data: days, then hours, then temperature and rain.

Two steps into a grid

Each pair of brackets goes one level deeper. Tap each part to see its job.

Part 1 of 3

Tap any part of the code below, or press Next.1 of 3 explored

grid:A list of rows, for example [[1, 2, 3], [4, 5, 6]].

Reach inside

Pick an example, change it, then press Run. Say what you expect to see before you press.

Example 1 of 6Grid

Row first, then column.

Your turn: Print the number in the very middle, then the bottom-left corner.

Python
grid = [[1, 2, 3],
        [4, 5, 6],
        [7, 8, 9]]
print(grid[1][2])
print(grid[2])
for row in grid:
    print(row)
Output
Press Run to see what it prints.

Watch X win

Press Step to run one line at a time. The board is a list of three rows.

Ready. Press Step to run the first line.

  1. board = [["X", "O", "."], [".", "X", "."], ["O", ".", "."]]
  2. board[2][2] = "X"
  3. middle = board[1][1]
  4. diagonal = [board[0][0], board[1][1], board[2][2]]
  5. print(middle)
  6. print(diagonal == ["X", "X", "X"])

Output so far

Nothing printed yet.

What Python does

Python reads the program from the top. Nothing has run yet.

Names

None yet.

Quick guesses

Guess first, then read why. A wrong guess is where the learning happens. Nothing here is scored.

Question 1 of 6

1.Row, then column: what prints?

g = [[1, 2], [3, 4]]
print(g[1][0])

0 of 6 answered

Common nesting misconceptions

Each card is something beginners often believe. Tap it to see what Python really does.

Misconception 1 of 4

Notes

Everything above, in words. Open it when you want the full explanation.

Read the notesOpen

Collections inside collections

Any list or dictionary can hold other lists and dictionaries. Nothing new is needed in the language: you combine what you already know, one level at a time.

Lists of lists: grids

A list whose items are lists is a natural way to store a grid, such as a seating plan or a game board. The first index picks a row and the second picks a column inside it.

Try it 1: edit me, then Run
board = [
    ["X", "O", "X"],
    [" ", "X", "O"],
    ["O", " ", "X"],
]
print(board[0])        # ['X', 'O', 'X'], the whole first row
print(board[1][2])     # O, row 1, column 2
board[1][0] = "O"      # change one square
Output
Press Run to see what it prints.

Read board[1][2] from left to right: board[1] gives a row, and [2] picks an item from that row. Looping over a grid usually needs two loops, one for rows and one for the items in each row.

Try it 2: edit me, then Run
for row in board:
    print(" | ".join(row))
Output
Press Run to see what it prints.

Lists of dictionaries: tables of records

When each item has several named parts, use a dictionary per item and keep them in a list. This is the shape of a spreadsheet: the list holds the rows and each dictionary holds one row's columns.

Try it 3: edit me, then Run
pupils = [
    {"name": "Amina", "age": 11, "marks": [80, 90, 100]},
    {"name": "Bilal", "age": 12, "marks": [70, 75, 80]},
]
print(pupils[1]["name"])         # Bilal
print(pupils[0]["marks"][-1])    # 100
for pupil in pupils:
    average = sum(pupil["marks"]) / len(pupil["marks"])
    print(f"{pupil['name']}: {average:.1f}")
Output
Press Run to see what it prints.

Each step of a chain like pupils[0]["marks"][-1] uses the right kind of index for the value at that level: a position for a list, a key for a dictionary. When a chain fails, split it and print each step to see which level is not what you expected.

Dictionaries of lists and of dictionaries

Turn the shape around when you look things up by name. A dictionary of lists groups items under a key, and a dictionary of dictionaries gives each key a whole record.

Try it 4: edit me, then Run
by_class = {"5A": ["Amina", "Cy"], "5B": ["Bilal"]}
by_class["5B"].append("Dee")
print(len(by_class["5B"]))       # 2

stock = {
    "tea": {"price": 2.5, "qty": 40},
    "cake": {"price": 3.0, "qty": 6},
}
stock["cake"]["qty"] -= 1
print(stock["cake"])             # {'price': 3.0, 'qty': 5}
Output
Press Run to see what it prints.

Choosing a shape is a design decision. Ask how the data will be used most: if you mostly go through every record, a list of dictionaries is easiest; if you mostly look one record up by name, a dictionary keyed by that name is faster and clearer.

Building nested data step by step

Nested data is usually built up while a program runs rather than typed out in full. Start with the empty outer collection, then add the inner ones one at a time. For a dictionary of lists, check whether the key exists before appending, or use setdefault(key, []) from the dictionaries lesson. For a list of dictionaries, build each record as a small dictionary and append it. Printing the structure after each step while you develop is the quickest way to make sure its shape is what you planned. Once the shape is right, the loops that read it almost write themselves, because each level of nesting becomes one level of loop.

The shared row trap

[0] * 3 makes a list of three zeros, so it is tempting to make a grid with [[0] * 3] * 3. That does not work, because * repeats the same inner list three times. All three rows are one list with three names.

Try it 5: edit me, then Run
grid = [[0] * 3] * 3
grid[0][0] = 9
print(grid)            # [[9, 0, 0], [9, 0, 0], [9, 0, 0]]
Output
Press Run to see what it prints.

Build a grid with a loop instead, so that every row is a new list.

Try it 6: edit me, then Run
grid = []
for _ in range(3):
    grid.append([0] * 3)
grid[0][0] = 9
print(grid)            # [[9, 0, 0], [0, 0, 0], [0, 0, 0]]
Output
Press Run to see what it prints.

The inner [0] * 3 is safe because numbers cannot be changed in place; only repeating a list of lists causes trouble.

Copying nested data

copy() makes a shallow copy: a new outer list that still holds the same inner lists. Changing an inner list through the copy changes the original too. For a fully independent copy, use deepcopy() from the copy module, which copies every level.

Try it 7: edit me, then Run
import copy
original = [[1, 2], [3, 4]]
shallow = original.copy()
deep = copy.deepcopy(original)
shallow[0].append(99)
print(original)        # [[1, 2, 99], [3, 4]], changed through shallow
print(deep)            # [[1, 2], [3, 4]], fully separate
Output
Press Run to see what it prints.

import copy loads one of Python's standard library modules, which the Practical Python course covers in detail. For now, remember the line: when you copy something nested and plan to change the inside, use copy.deepcopy().

Missing keys deep inside

Data from outside a program often has optional parts. user["address"]["city"] raises KeyError if there is no address. Chaining get() with an empty dictionary as the default keeps going safely and gives None or your own default at the end.

Try it 8: edit me, then Run
user = {"name": "Ana"}
city = user.get("address", {}).get("city", "Unknown")
print(city)            # Unknown
Output
Press Run to see what it prints.

Keep nesting shallow

Two or three levels are easy to work with. Beyond that, code fills with long chains of brackets that are hard to read and easy to get wrong. If you find yourself writing data[0]["items"][2]["tags"][1], pull the inner part into a well-named variable first, such as first_order = data[0], and work from there.

Syntax

The general shape of the statements in this lesson.

syntax.py
grid[row][col]                     # list of lists
records[0]["name"]                 # list of dictionaries
groups["5A"].append("Cy")          # dictionary of lists
stock["tea"]["qty"] -= 1           # dictionary of dictionaries
for row in grid:  for record in records:
grid = []; for _ in range(3): grid.append([0] * 3)   # separate rows
import copy; copy.deepcopy(data)   # copy every level
d.get("a", {}).get("b", default)   # safe nested lookup
Output
Press Run to see what it prints.

Worked examples

Read the problem, run the code, then read why it works.

Example 1 of 2

A class report from records

Beginner

Given a list of pupil records, print each pupil's average and find the pupil with the highest average.

Python
pupils = [
    {"name": "Amina", "marks": [80, 90, 100]},
    {"name": "Bilal", "marks": [70, 75, 80]},
    {"name": "Chen", "marks": [95, 85, 90]},
]
best_name = ""
best_average = 0
for pupil in pupils:
    average = sum(pupil["marks"]) / len(pupil["marks"])
    print(f"{pupil['name']}: {average:.1f}")
    if average > best_average:
        best_average = average
        best_name = pupil["name"]
print("Top:", best_name)
Output
Press Run to see what it prints.

Predict first

How it works(open after your guess)

The loop variable pupil is one dictionary at a time, so pupil["marks"] is that pupil's list. Chen ties with Amina, but the test is >, not >=, so the first top scorer stays. Ties are a decision worth making on purpose.

Common pitfalls

Mistakes people make with this topic, and what to write instead.

Pitfall 1 of 3

Repeating a row with *

Spot the bug

Can you see what is wrong? Run it to watch it go wrong, then open the fix.

Buggy code: run it
grid = [[0] * 2] * 2
grid[0][1] = 5
print(grid)
Output
Press Run to see what it prints.
Show what goes wrong and the fix

What happens

Prints [[0, 5], [0, 5]]; both rows changed

Write this instead

grid = []
for _ in range(2):
    grid.append([0] * 2)
grid[0][1] = 5
print(grid)

Why it happens

The outer * repeats the same inner list, so both rows are one list.

In the real world

Where this shows up in software people use every day.

  1. Weather readings by city

    Weather

    A weather site keeps a week of daily highs for each city as a dictionary of lists and shows each city's warmest day.

    Why Python fits

    Each key leads to a whole list, so ordinary list tools work on it: max() finds the highest value and index() finds its position, which then picks the matching day name.

    Python
    highs = {
        "Oslo": [12, 14, 11, 15, 13],
        "Rome": [24, 27, 26, 25, 28],
    }
    days = ["Mon", "Tue", "Wed", "Thu", "Fri"]
    for city, temps in highs.items():
        warmest = max(temps)
        day = days[temps.index(warmest)]
        print(f"{city}: warmest {warmest} C on {day}")
    Output
    Press Run to see what it prints.

Key takeaways

Tick each one you could explain to a friend.

0 of 5

Common questions

Guess the answer first, then open it.

How deep can nesting go?

As deep as you like, but past two or three levels code gets hard to read. Pull inner parts into named variables.

Is this what JSON looks like?

Yes. JSON objects become dictionaries and JSON arrays become lists. Reading JSON files is covered in Practical Python.

How do I print nested data neatly?

Loop and print one level at a time, or for a quick look use import pprint and pprint.pprint(data), which spreads it over several lines.

Your notes

Sign in to keep private notes alongside this lesson.

Sign in to take notes

Where to go next

The quiz and the Lab live on their own pages, so this lesson stays about learning.

Finished this lesson?

Create an ID or sign in to save your progress across devices.

Create ID to save
Lessons done in this module0/4 complete
Quiz

Check what you learned

12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.

Lab

Keep going in the Lab

7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.

Review

Spaced review

Questions you miss in a quiz come back on a spaced schedule, so what you learned here sticks.

This lesson at a glance

The 8 lines of code this lesson uses, each with a short note. Keep it open while you do the quiz and the Lab.

What else you can search for and explore

Curious to go further? Each card opens a web search in a new tab.

References

Look things up here whenever you need the exact details.