Working With Nested Data
Real-world data is rarely flat. When you fetch data from an API or read a JSON file, you'll encounter nested structures — lists containing dictionaries, dictionaries containing lists, and combinations of both.
Lists of Dictionaries
This is perhaps the most common pattern. Each item in the list is a dictionary representing one record:
users = [
{"name": "Alice", "age": 30},
{"name": "Bob", "age": 25},
{"name": "Charlie", "age": 35}
]
To access a specific user's name, chain the accesses:
print(users[0]["name"]) # Alice
First, users[0] gets the first dictionary. Then ["name"] gets the name value from that dictionary.
Looping Through Nested Data
To process all users, loop through the list. Each iteration gives you one dictionary:
for user in users:
print(f"{user['name']} is {user['age']} years old")
Output:
Alice is 30 years old
Bob is 25 years old
Charlie is 35 years old
Inside the loop, user is a dictionary, so you access its values with keys.
Dictionaries Containing Lists
The nesting can go the other way too:
classroom = {
"teacher": "Ms. Smith",
"students": ["Alice", "Bob", "Charlie"],
"room": 101
}
To loop through the students:
for student in classroom["students"]:
print(student)
First, classroom["students"] gets the list. Then the for loop iterates over that list.
Deeper Nesting
Data can nest multiple levels deep:
company = {
"name": "TechCorp",
"departments": [
{
"name": "Engineering",
"employees": ["Alice", "Bob"]
},
{
"name": "Marketing",
"employees": ["Charlie", "Diana"]
}
]
}
# Get first department's first employee
print(company["departments"][0]["employees"][0]) # Alice
Read this left to right: get departments (a list), get index 0 (a dictionary), get employees (a list), get index 0 (a string).
Tips for Nested Data
When working with complex structures:
- Print intermediate values to understand the shape
- Work from outside in — access one level at a time
- Use descriptive variable names in loops to track what you're working with
# Clear naming helps
for department in company["departments"]:
for employee in department["employees"]:
print(f"{employee} works in {department['name']}")