Python Tutorial
Python Nested Dictionaries
A dictionary can contain dictionaries. That is a nested dictionary.
Create a Nested Dictionary
Each value can be another dict.
myfamily = {
"child1": {"name": "Emil", "year": 2004},
"child2": {"name": "Tobias", "year": 2007},
"child3": {"name": "Linus", "year": 2011},
}
print(myfamily["child2"]["name"])Loop Nested Dictionaries
Loop the outer dict, then the inner one.
myfamily = {
"child1": {"name": "Emil", "year": 2004},
"child2": {"name": "Tobias", "year": 2007},
}
for key, obj in myfamily.items():
print(key)
for y in obj:
print(y + ":", obj[y])📘 Real-World Deep Dive
Nested dicts describe hierarchical data (config, JSON, trees). Knowing how to walk, query, and rewrite them is core to any non-trivial Python program.
Real-Life Scenario
A typical multi-tenant config tree loaded from YAML: walk it, detect misconfigurations, and surface a flat list of issues.
Real-Life Example
def walk(node, path=()):
yield path, node
if isinstance(node, dict):
for k, v in node.items():
yield from walk(v, path + (k,))
elif isinstance(node, list):
for i, v in enumerate(node):
yield from walk(v, path + (i,))
config = {
"service": {
"name": "api",
"db": {"host": "db.local", "port": 5432, "ssl": True},
"features": {"beta": ["search_v2", "ai_suggest"]},
},
"limits": {"max_connections": 100},
}
issues: list[str] = []
for path, value in walk(config):
if isinstance(value, int) and value <= 0:
issues.append(f"non-positive integer at {'/'.join(map(str, path))}: {value}")
if path and path[-1] == "ssl" and isinstance(value, dict):
issues.append(f"nested-typed ssl at {'/'.join(map(str, path))}")
for line in issues:
print(line)
print("OK" if not issues else "FIX")Expected Output
OKCommon mistakes
- A deeply nested dict is usually a sign that a class / dataclass would be clearer.
- Mixing string keys and int indices within the same structure is a regular source of bugs.
- Recursing on a hundred-thousand-node tree by Python calls alone is slow; consider
itertoolsor an iterative walk.
🚀 Performance & Best Practices
- Build a flat address:
[(path, value) for path, value in walk(d)], then index it. - Use
dataclasses+ a custom serializer for typed trees — much cheaper than raw dicts. - If you only need one level, prefer
d.get("a", {}).get("b")over a full traversal.
🧪 Try It Yourself
- Add a checker that warns when a
"password"key appears in plain text. - Convert the flat issue list into a regex that finds the same pattern in ad-hoc strings.
- Compare the walker above with an iterative version using an explicit stack.