SyntaxStudy
Sign Up
Python Intermediate 9 min read

Nested Dictionaries

Nested Dictionaries

Dictionaries can contain other dictionaries as values, enabling you to represent hierarchical data structures.

Creating Nested Dicts

company = {
    "name": "TechCorp",
    "departments": {
        "engineering": {
            "head": "Alice",
            "headcount": 45,
            "budget": 2_000_000
        },
        "marketing": {
            "head": "Bob",
            "headcount": 12,
            "budget": 500_000
        }
    }
}

Accessing Deeply Nested Data

print(company["departments"]["engineering"]["head"])  # Alice
print(company["departments"]["marketing"]["budget"])  # 500000

Safe Deep Access

eng = company.get("departments", {}).get("engineering", {})
print(eng.get("headcount", 0))  # 45

Updating Nested Values

company["departments"]["engineering"]["headcount"] = 50
company["departments"]["hr"] = {"head": "Carol", "headcount": 5}

Iterating Nested Dicts

for dept, info in company["departments"].items():
    print(f"{dept}: {info['head']} leads {info['headcount']} people")
Example
users = {
    "u001": {"name": "Alice", "roles": ["admin", "user"]},
    "u002": {"name": "Bob",   "roles": ["user"]},
}

for uid, data in users.items():
    print(f"{uid}: {data['name']} => {data['roles']}")

users["u003"] = {"name": "Carol", "roles": ["user"]}
users["u001"]["roles"].append("superadmin")
print(users["u001"])
Pro Tip

For deeply nested structures, consider using a library like pydantic or a dataclass so you get type checking and clear error messages.