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
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.
grid = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
print(grid[1][2])
print(grid[2])
for row in grid:
print(row)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.
- board = [["X", "O", "."], [".", "X", "."], ["O", ".", "."]]
- board[2][2] = "X"
- middle = board[1][1]
- diagonal = [board[0][0], board[1][1], board[2][2]]
- print(middle)
- 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 notesNotesOpenClose
Syntax
The general shape of the statements in this lesson.
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 lookupPress 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
Given a list of pupil records, print each pupil's average and find the pupil with the highest average.
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)Press Run to see what it prints.Predict first
How it works(open after your guess)
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.
grid = [[0] * 2] * 2 grid[0][1] = 5 print(grid)
Press Run to see what it prints.Show what goes wrong and the fixWhat goes wrong and the fix
In the real world
Where this shows up in software people use every day.
- Weather
Weather readings by city
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 andindex()finds its position, which then picks the matching day name.Pythonhighs = { "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}")OutputPress 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?
Is this what JSON looks like?
How do I print nested data neatly?
Your notes
Sign in to keep private notes alongside this lesson.
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.
Check what you learned
12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.
Keep going in the Lab
7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.
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.