Nested Dictionaries

A dictionary can contain other dictionaries, known as nested dictionaries. This is useful for representing more complex data structures, such as JSON data, or any data that has a hierarchical relationship.

Creating a Nested Dictionary:

You can create a nested dictionary by defining dictionaries within dictionaries:

Python
# Creating a nested dictionary
family = {
    "child1": {
        "name": "Alice",
        "year": 2005
    },
    "child2": {
        "name": "Bob",
        "year": 2007
    },
    "child3": {
        "name": "Charlie",
        "year": 2010
    }
}

print(family)

Accessing Nested Items:

You can access items in a nested dictionary by chaining key references:

Python
# Access the name of the first child
print(family["child1"]["name"])  # Output: Alice

Adding Items to a Nested Dictionary:

You can add items to a nested dictionary just like you would with a normal dictionary:

Python
# Add a new child
family["child4"] = {"name": "Daisy", "year": 2012}
print(family)

Modifying Items in a Nested Dictionary:

To modify an item in a nested dictionary, you can reference the keys and assign a new value:

Python
# Modify the year of the first child
family["child1"]["year"] = 2006
print(family["child1"])  # Output: {"name": "Alice", "year": 2006}

Removing Items from a Nested Dictionary:

You can remove an item from a nested dictionary using the del statement:

Python
# Remove the second child
del family["child2"]
print(family)

Iterating Through a Nested Dictionary:

You can loop through a nested dictionary to access all keys and values:

Python
# Loop through all children
for child, details in family.items():
    print(f"{child}:")
    for key, value in details.items():
        print(f"  {key}: {value}")

# Output:
# child1:
#   name: Alice
#   year: 2006
# child3:
#   name: Charlie
#   year: 2010
# child4:
#   name: Daisy
#   year: 2012

Nested dictionaries are powerful for storing data that has a hierarchical structure, making them ideal for complex data representations such as configurations, records, and more.