Data Structures18 min read
Nested Structures
Work confidently with nested lists/dicts: reading and writing deeply, loops, safe access patterns, and a strong mental model with diagrams.
David Miller
November 17, 2025
4.7k207
Real data is often nested.
Examples:
- API JSON
- database records
- configuration files
Nested list (2D list)
matrix = [
[1, 2, 3],
[4, 5, 6]
]
print(matrix[0][1]) # 2
Nested dict (JSON style)
user = {
"id": 101,
"profile": {"name": "Tom", "city": "Austin"}
}
print(user["profile"]["name"])
Safe access pattern
Use get() to avoid KeyError:
city = user.get("profile", {}).get("city", "Unknown")
print(city)
Loop through nested structures
for row in matrix:
for value in row:
print(value)
Graph: nested access
flowchart LR
A[user] --> B[profile]
B --> C[name]
B --> D[city]
Remember
- Nested data is normal in real apps
- Use get() for safe access
- Understand references when nested lists are copied
#Python#Beginner#Nested