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

  1. Build the structure layer by layer.
  2. Access nested values with chained brackets.
  3. Use .get() or try/except to avoid KeyError on 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"] raises KeyError; 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.