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"]) # 500000Safe Deep Access
eng = company.get("departments", {}).get("engineering", {})
print(eng.get("headcount", 0)) # 45Updating 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")