Python Practice › Dictionary Programs › Program 65
Depth of a nested dictionary
Write a Python program to find the depth of a nested dictionary.
Input
{"a": 1, "b": {"c": {"d": {}}}}Output
4
Approach
- Depth is 1 plus the deepest child dictionary’s depth (recursion).
Solution
def depth(d): if not isinstance(d, dict) or not d: return 1 if isinstance(d, dict) else 0 return 1 + max(depth(v) for v in d.values()) print(depth({"a": 1, "b": {"c": {"d": {}}}}))Output
4
Line by line
Lines 2-3
An empty dict has depth 1; a non-dict value adds nothing.
Line 4
Each level adds 1 to the deepest value below it.
Learn the concept
New to this topic? Read the lesson, then come back.