- Courses
- 💻Programming Languages
- 🐍Python
- Core Data Structures
- Iterating Over Complex Data
On this page
Iterating Over Complex Data
By Enrico Hochkoeppler
Web Developer & TutoriaLibre Founder
Why This Lesson Matters
Real‑world data is rarely flat. APIs return nested JSON, applications store multi‑level configurations, and programs often manage lists of dictionaries, dictionaries of lists, or even deeper combinations. To work effectively with such structures, you must master multi‑level iteration.
This lesson teaches you how to navigate and process complex, nested data using loops, unpacking, and structured patterns.
Iterating Through Nested Lists
A nested list is a list where each element is itself a list.
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
Looping Through Rows
for row in matrix:
print(row)
Looping Through Every Value
for row in matrix:
for value in row:
print(value)
This pattern is essential for grid‑based data, tables, and numerical processing.
Iterating Through a List of Dictionaries
This is one of the most common real‑world structures, especially when working with JSON or API responses.
users = [
{"name": "Alice", "age": 30},
{"name": "Bob", "age": 25}
]
Looping Through Each Dictionary
for user in users:
print(user["name"], user["age"])
Looping Through Keys and Values
for user in users:
for key, value in user.items():
print(key, value)
This pattern is essential for data transformation and reporting.
Iterating Through Dictionaries Containing Lists
Dictionaries often store lists as values.
student = {
"name": "Sara",
"scores": [85, 90, 92]
}
Looping Through Nested Lists
for score in student["scores"]:
print(score)
This is common in analytics, grading systems, and configuration data.
Iterating Through Dictionaries of Dictionaries
Hierarchical data often uses nested dictionaries.
config = {
"database": {"host": "localhost", "port": 5432},
"api": {"endpoint": "/v1", "timeout": 30}
}
Looping Through Nested Keys
for section, settings in config.items():
print("Section:", section)
for key, value in settings.items():
print(" ", key, "=", value)
This pattern is essential for configuration parsing and structured data processing.
Iterating Through Mixed Structures
Real data often mixes lists, dictionaries, tuples, and sets.
Example:
data = {
"users": [
{"id": 1, "roles": ("admin", "editor")},
{"id": 2, "roles": ("viewer",)}
],
"active": {1, 3, 5}
}
Processing Mixed Types
for user in data["users"]:
print("User:", user["id"])
for role in user["roles"]:
print(" -", role)
for uid in data["active"]:
print("Active ID:", uid)
Understanding the structure is the key to iterating correctly.
Using Tuple Unpacking in Loops
Unpacking makes iteration cleaner and more expressive.
Unpacking Key‑Value Pairs
for key, value in config["database"].items():
print(key, value)
Unpacking Tuples in Lists
points = [(10, 20), (30, 40)]
for x, y in points:
print("x:", x, "y:", y)
Unpacking reduces indexing and improves readability.
Strategies for Iterating Over Unknown or Deeply Nested Data
When you don’t know the structure in advance, use these strategies:
1. Check the Type
if isinstance(item, dict):
...
elif isinstance(item, list):
...
2. Use Recursion for Arbitrary Depth
def walk(data):
if isinstance(data, dict):
for key, value in data.items():
walk(value)
elif isinstance(data, list):
for item in data:
walk(item)
else:
print(data)
This technique is powerful for exploring deeply nested JSON.
When to Use Each Pattern
- Nested loops — when structure depth is known
- Unpacking — when iterating over predictable pairs or tuples
- Type checks — when structure varies
- Recursion — when depth is unknown or arbitrary
- Dictionary iteration — when processing structured records
These patterns cover nearly all real‑world iteration scenarios.
Summary
Iterating over complex data requires understanding how lists, dictionaries, tuples, and sets combine into multi‑level structures. By mastering nested loops, unpacking, type‑based traversal, and recursive strategies, you gain the ability to process real‑world data confidently and efficiently.
Found this helpful? Share the knowledge...
... or support this project to keep it alive!
Previous
Nested Structures
Next
Guided Exercise: Build a Contact Book
-
Why This Lesson Matters
-
Iterating Through Nested Lists
- Looping Through Rows
- Looping Through Every Value
-
Iterating Through a List of Dictionaries
- Looping Through Each Dictionary
- Looping Through Keys and Values
-
Iterating Through Dictionaries Containing Lists
- Looping Through Nested Lists
-
Iterating Through Dictionaries of Dictionaries
- Looping Through Nested Keys
-
Iterating Through Mixed Structures
- Processing Mixed Types
-
Using Tuple Unpacking in Loops
- Unpacking Key‑Value Pairs
- Unpacking Tuples in Lists
-
Strategies for Iterating Over Unknown or Deeply Nested Data
- 1. Check the Type
- 2. Use Recursion for Arbitrary Depth
-
When to Use Each Pattern
-
Summary
