Andromeda
Note

Nesting (Python Data Structures)

Definition

The practice of storing one data structure inside another, such as a dictionary inside a list, a list inside a dictionary, or a dictionary inside another dictionary.

Why It Matters

Deeply nested code (‘The Pyramid of Doom’) is hard to read, hard to test, and prone to bugs. In Python, where readability is a core tenet, excessive nesting is a ‘code smell’ that indicates a lack of abstraction. Flattening your logic is the path to maintainability.

Core Concepts

  • Structural Combinations:
    • List of Dictionaries: Managing multiple similar objects (e.g., a list of alien objects).
    • List in a Dictionary: One key mapping to multiple values (e.g., pizza['toppings']).
    • Dictionary in a Dictionary: Hierarchical models (e.g., all_guests['Alice']['apples']).
# Example: List of Dictionaries
users = [
    {"username": "jdoe", "roles": ["admin", "editor"]},
    {"username": "asmith", "roles": ["viewer"]}
]

# Accessing nested data
print(users[0]["roles"][1]) # Output: editor
  • Traversing and Aggregating: To process nested data, use nested loops (e.g., a for loop to iterate through the main keys, and another to sum specific sub-values across the entire structure).
  • The .get() Pattern: When aggregating nested data, use .get(item, 0) to handle cases where a sub-key might be missing, ensuring the math doesn’t crash on a KeyError.

Connected Concepts