How do I work with nested lists and dictionaries in Python?
· Category: Python Programming
Short answer
Nested structures combine lists and dictionaries to represent hierarchical or tabular data. Access them by chaining indices or keys, and use get() or collections.defaultdict to handle missing paths gracefully.
Steps
- Build the structure layer by layer.
- Access nested values with chained brackets.
- Use
.get()ortry/exceptto avoidKeyErroron missing paths.
# Nested structure
users = {
"alice": {
"age": 30,
"roles": ["admin", "editor"]
},
"bob": {
"age": 25,
"roles": ["viewer"]
}
}
# Access
print(users["alice"]["roles"][0]) # admin
# Safe access with get
role = users.get("charlie", {}).get("roles", [])
print(role)
# Building nested structures
data = {}
for user, detail in [("alice", {"city": "NYC"}), ("bob", {"city": "LA"})]:
data.setdefault(user, {}).update(detail)
print(data)
Tips
json.loads()often produces nested dicts and lists from API responses.pandas.json_normalize()flattens nested JSON into a DataFrame.- Use recursion or a stack to traverse deeply nested trees of unknown depth.
copy.deepcopy()is essential when cloning nested mutable structures.
Common issues
users["missing"]["key"]raisesKeyError; use.get()for optional fields.- Accidentally sharing inner lists or dicts across multiple outer keys causes spooky action at a distance.
- Deeply nested structures become hard to read and maintain; consider dataclasses or Pydantic models for complex schemas.