Skip to main content
Editor

Working with Nested Lists, Dicts, and Complex Data Structures

Intermediate25 min6 exercises85 XP

Leer en españolЧитать на русскомLer em portuguêsอ่านภาษาไทย

0/6 exercises

Think about a school. A school has classrooms. Each classroom has students. Each student has a name, an age, and a list of grades. That's data inside data inside data - nested data.

Nested data is everywhere in real programming. A social media app stores users who have posts, and each post has comments. A game stores levels that contain enemies, and each enemy has stats. An online store has categories containing products with reviews.

In this tutorial, you'll learn how to build, access, modify, and loop through nested lists and dictionaries. These skills are essential for working with real-world data, especially JSON from web APIs.

How Do Lists Inside Lists Work?

A list can contain other lists as its items. This creates a two-dimensional structure, like a grid or a table. Think of a spreadsheet - rows and columns.

A nested list representing a grid
# A 3x3 grid (like a tic-tac-toe board)
board = [
['X', 'O', 'X'],
['O', 'X', 'O'],
['X', ' ', 'O'],
]
for row in board:
print(row)
Output
['X', 'O', 'X']
['O', 'X', 'O']
['X', ' ', 'O']

To access an item in a nested list, you use two sets of square brackets. The first bracket picks the row. The second bracket picks the column.

Accessing items with double indexing
board = [
['X', 'O', 'X'],
['O', 'X', 'O'],
['X', ' ', 'O'],
]
# board[row][column]
print(board[0][0]) # X (top-left)
print(board[1][1]) # X (center)
print(board[2][1]) # (space) (bottom-middle)
Output
X
X

You can also modify items using the same double-bracket syntax. This is how you would place a move in a tic-tac-toe game.

Modifying items in a nested list
board = [
[' ', ' ', ' '],
[' ', ' ', ' '],
[' ', ' ', ' '],
]
# Place some moves
board[0][0] = 'X' # top-left
board[1][1] = 'O' # center
board[0][2] = 'X' # top-right
for row in board:
print(row)
Output
['X', ' ', 'X']
[' ', 'O', ' ']
[' ', ' ', ' ']

How Do Nested Dictionaries Work?

A dictionary value can itself be another dictionary. This creates a tree-like structure where you drill down through keys to reach the data you need.

Nested dictionaries with chained key access
school = {
'Room 101': {
'teacher': 'Ms. Smith',
'subject': 'Math',
'students': 28,
},
'Room 102': {
'teacher': 'Mr. Jones',
'subject': 'English',
'students': 25,
},
}
print(school['Room 101']['teacher']) # Ms. Smith
print(school['Room 102']['students']) # 25
Output
Ms. Smith
25

Each set of square brackets digs one level deeper. school['Room 101'] gives you the inner dictionary. Then ['teacher'] gives you the value inside that inner dictionary.

You can also add new keys or update values at any level.

Modifying nested dictionaries
school = {
'Room 101': {
'teacher': 'Ms. Smith',
'subject': 'Math',
},
}
# Update an existing value
school['Room 101']['subject'] = 'Algebra'
# Add a new key to the inner dict
school['Room 101']['students'] = 30
# Add an entirely new room
school['Room 103'] = {
'teacher': 'Ms. Lee',
'subject': 'Science',
'students': 22,
}
for room, info in school.items():
print(f"{room}: {info['teacher']} teaches {info['subject']}")
Output
Room 101: Ms. Smith teaches Algebra
Room 103: Ms. Lee teaches Science

Lists of Dictionaries: The Most Common Pattern

The most common nested structure in real-world programming is a list of dictionaries. Each dictionary represents one record - a student, a product, a user - and the list holds all the records together.

If you've ever seen data from a web API or a database, it almost always looks like a list of dictionaries.

A list of dictionaries: student records
students = [
{'name': 'Alice', 'age': 15, 'grade': 92},
{'name': 'Bob', 'age': 16, 'grade': 85},
{'name': 'Charlie', 'age': 15, 'grade': 97},
]
# Access a specific student
print(students[0]['name']) # Alice
print(students[2]['grade']) # 97
# Loop through all students
for student in students:
print(f"{student['name']} is {student['age']} and scored {student['grade']}")
Output
Alice
97
Alice is 15 and scored 92
Bob is 16 and scored 85
Charlie is 15 and scored 97

The pattern is always list[index][key]. The index picks which dictionary. The key picks which value inside that dictionary.

How to Access Deeply Nested Data Safely

Real-world data can be nested several levels deep. A company has departments, each department has teams, each team has members. Accessing deeply nested data means chaining multiple brackets.

Chaining brackets for deep access
company = {
'engineering': {
'backend': {
'members': ['Alice', 'Bob'],
'lead': 'Alice',
},
'frontend': {
'members': ['Charlie', 'Diana'],
'lead': 'Charlie',
},
},
}
# Get the backend team lead
print(company['engineering']['backend']['lead']) # Alice
# Get the second frontend team member
print(company['engineering']['frontend']['members'][1]) # Diana
Output
Alice
Diana

The danger with deep nesting is that any missing key causes a KeyError. If the data might be incomplete, use the .get() method, which returns None (or a default value) instead of crashing.

Safe nested access with .get()
user = {
'name': 'Alice',
'profile': {
'bio': 'Python developer',
},
}
# Safe access with .get()
print(user.get('profile', {}).get('bio', 'No bio')) # Python developer
print(user.get('profile', {}).get('website', 'No site')) # No site
print(user.get('settings', {}).get('theme', 'default')) # default
Output
Python developer
No site
default

How to Loop Through Nested Data Structures

When you have nested data, you often need nested loops. The outer loop goes through the top-level items, and the inner loop goes through the items inside each one. Sometimes a function does the inner work for you: in the first example below, sum() and len() handle each inner list, so one loop is enough.

Looping through a dict of lists
# Each subject with its list of grades
classes = {
'Math': [85, 92, 78, 95],
'English': [88, 76, 91],
'Science': [93, 87, 82, 79, 95],
}
for subject, grades in classes.items():
average = sum(grades) / len(grades)
print(f"{subject}: average = {average:.1f}")
Output
Math: average = 87.5
English: average = 85.0
Science: average = 87.2
Looping through a 2D grid with enumerate
# Nested list: a grid of numbers
grid = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
]
# Print each number with its position
for row_index, row in enumerate(grid):
for col_index, value in enumerate(row):
print(f"grid[{row_index}][{col_index}] = {value}")
Output
grid[0][0] = 1
grid[0][1] = 2
grid[0][2] = 3
grid[1][0] = 4
grid[1][1] = 5
grid[1][2] = 6
grid[2][0] = 7
grid[2][1] = 8
grid[2][2] = 9

For lists of dictionaries, a single loop is usually enough because each dictionary is one complete record.

Filtering a list of dicts with nested list checks
products = [
{'name': 'Laptop', 'price': 999, 'tags': ['electronics', 'computers']},
{'name': 'Book', 'price': 15, 'tags': ['education', 'reading']},
{'name': 'Phone', 'price': 699, 'tags': ['electronics', 'mobile']},
]
# Find all electronics
for product in products:
if 'electronics' in product['tags']:
print(f"{product['name']}: ${product['price']}")
Output
Laptop: $999
Phone: $699

How to Build Nested Data Structures from Scratch

You don't always receive nested data - sometimes you need to build it yourself. A common pattern is starting with an empty structure and adding items inside a loop.

Building a dict of lists by grouping
# Build a dictionary that groups words by their first letter
words = ['apple', 'avocado', 'banana', 'blueberry', 'cherry', 'coconut']
by_letter = {}
for word in words:
first = word[0]
if first not in by_letter:
by_letter[first] = []
by_letter[first].append(word)
for letter, group in by_letter.items():
print(f"{letter}: {group}")
Output
a: ['apple', 'avocado']
b: ['banana', 'blueberry']
c: ['cherry', 'coconut']

Another common task is transforming flat data into nested structures. For example, turning separate lists of names, ages, and grades into a list of dictionaries.

Combining parallel lists into a list of dicts
# Transform parallel lists into a list of dicts
names = ['Alice', 'Bob', 'Charlie']
ages = [15, 16, 15]
grades = [92, 85, 97]
students = []
for i in range(len(names)):
student = {
'name': names[i],
'age': ages[i],
'grade': grades[i],
}
students.append(student)
for s in students:
print(s)
Output
{'name': 'Alice', 'age': 15, 'grade': 92}
{'name': 'Bob', 'age': 16, 'grade': 85}
{'name': 'Charlie', 'age': 15, 'grade': 97}

Practice Exercises

Access Nested List Items
Write Code

You have a 3x3 grid of numbers. Print the center value (row 1, column 1), then print the bottom-right value (row 2, column 2). Each on a separate line.

grid = [
[10, 20, 30],
[40, 50, 60],
[70, 80, 90],
]
# Print the center value
# Print the bottom-right value
Predict the Output: Nested Dict Access
Predict Output

Read the code carefully. What will it print? Type the exact output.

data = {
'user': {
'name': 'Alice',
'scores': [80, 90, 100],
},
}
print(data['user']['name'])
print(data['user']['scores'][2])
Find the Highest Scorer
Write Code

Loop through the list of students and find the one with the highest grade. Print their name and grade in the format: Best: Name (Grade)

students = [
{'name': 'Alice', 'grade': 88},
{'name': 'Bob', 'grade': 95},
{'name': 'Charlie', 'grade': 72},
{'name': 'Diana', 'grade': 91},
]
# Find and print the highest scorer
Group Words by First Letter
Write Code

Group the words by their first letter into a dictionary. Then print each group on a separate line in the format: letter: [words]

Print the letters in sorted order.

words = ['ant', 'bear', 'apple', 'bat', 'cat', 'cow']
# Group by first letter and print
Fix the Bug: Nested List Trap
Fix the Bug

This code tries to create a 3x3 grid and set only the center cell to "X". But something is wrong - run it and see! Fix the bug so only the center cell is "X" and all other cells remain ".".

Print each row on a separate line.

row = ['.'] * 3
grid = [row] * 3
grid[1][1] = 'X'
for r in grid:
print(r)
Calculate Class Averages
Write Code

You have a dictionary where each key is a class name and each value is a list of student dictionaries. Calculate the average grade for each class and print it in the format: ClassName: average

Round each average to 1 decimal place. Print classes in alphabetical order.

classes = {
'Math': [
{'name': 'Alice', 'grade': 90},
{'name': 'Bob', 'grade': 80},
],
'English': [
{'name': 'Charlie', 'grade': 85},
{'name': 'Diana', 'grade': 95},
{'name': 'Eve', 'grade': 78},
],
}
# Calculate and print each class average

Harder problems

More problems on this topic: Working with data

Related Tutorials

Was this tutorial helpful?