Lesson 15 of 30
In progress
Nested data: records inside collections
Model records as lists of dictionaries, build tables, and read nested values without losing track of which level you are on.
Real data rarely arrives as a flat list of numbers. It arrives as students with names and scores, orders with items and totals, or tables with rows and columns. Nested collections are how you keep that shape instead of flattening it into confusion.
What you will learn
- Store records as dictionaries inside a list.
- Read and update nested values one level at a time.
- Build and traverse a table without losing your place.
A record is a dictionary, a table is a list of records
The most useful structure in Python is a list of dictionaries. Each dictionary is one row, and each key is a column.
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
print(students[0]["name"])
print(students[2]["score"])
for student in students:
print(f"{student['name']}: {student['score']}")
Press Run to see the output.
Read the brackets from the outside in: students[0] is one dictionary, then ["name"] picks a value from it. In an f-string, the inner quotes must be single quotes, because the outer quotes are double. That is a syntax detail people hit constantly.
Adding a record is append, and updating a field is a normal assignment:
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
students.append({"name": "Ravi", "score": 72})
students[0]["score"] = 90
students[1]["passed"] = True
print(students)
Press Run to see the output.
That last line adds a key to one record only. Dictionaries do not share a schema, which is flexible but means a typo in a key name creates a new field instead of raising an error. Keep key names consistent by writing them once, or by building records through a small function.
Filtering and summarising
Because each record is a dictionary, summarising is a loop with a condition.
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
total = 0
passed = []
for student in students:
total += student["score"]
if student["score"] >= 80:
passed.append(student["name"])
print("Average:", round(total / len(students), 1))
print("Merit:", passed)
Press Run to see the output.
Accessing student["score"] assumes the key exists. When imported data may be incomplete, use student.get("score", 0) so one missing field does not stop the whole report. Print the count of records you processed as well as the average; a silent zero for a missing field changes the average, and the count is how you notice.
Tables as lists of lists
A matrix is a list where every item is a row, and every row is a list of cells.
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
print(grid[1][2])
print(len(grid))
print(len(grid[0]))
for row in grid:
for cell in row:
print(cell, end=" ")
print()
Press Run to see the output.
grid[1][2] is row 1, column 2, which is 6. Nested loops are natural here: outer for rows, inner for cells. Print a newline after each row so the output looks like a table.
To build a grid, create a new list per row. [[0] * 3] * 3 looks clever and is wrong: all three rows are the same list, so changing one changes all of them.
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
Press Run to see the output.
The comprehension builds a distinct list for each row. The same warning applies to copying nested data: grid[:] copies the outer list but shares the rows.
Dictionaries of lists
The other direction groups values under a label, which is how you bucket data without knowing the buckets in advance.
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
for level, name in [("beginner", "Ana"), ("advanced", "Mei"), ("beginner", "Ravi")]:
by_level.setdefault(level, []).append(name)
print(by_level)
Press Run to see the output.
setdefault returns the existing list or creates an empty one, then append adds to it. Without it you would need an if level not in by_level branch first. This pattern is worth remembering for grouping anything: orders by customer, posts by tag, scores by grade.
copy = grid[:] then copy[0][0] = 99 also changes grid[0][0]. The slice copies the outer list only; the inner lists are shared. Use copy = [row[:] for row in grid] for one level of deep copying, and copy.deepcopy when nesting goes deeper.
Given a list of orders, each with a customer and a total, print each customer’s order count and total spent, sorted by total spent from highest to lowest.
Show solution
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
summary = {}
for order in orders:
name = order["customer"]
entry = summary.setdefault(name, {"count": 0, "spent": 0})
entry["count"] += 1
entry["spent"] += order["total"]
ranked = sorted(summary.items(), key=lambda pair: pair[1]["spent"], reverse=True)
for name, entry in ranked:
print(f"{name}: {entry['count']} orders, {entry['spent']} total")
Press Run to see the output.
setdefault creates the inner dictionary once per customer, then the same lines update counts and totals. The lambda reaches into the value dictionary for the sort key.
Recap
- A list of dictionaries models a table: one dictionary per row.
- Read nested values one level at a time, and use
getwhen fields may be missing. - Copy nested data explicitly; slices are shallow.
You have finished the data-structures module. Next, you will write your own functions so repeated logic has a name and a single place to change.
When should I use a class instead of a dictionary?
How deep should nesting go?
Progress is saved in this browser only. No account, no email.