Depth of a nested dictionary

MediumDictionary Programs · 65 of 94

Write a Python program to find the depth of a nested dictionary.

Advertisement
Input
{"a": 1, "b": {"c": {"d": {}}}}
Output
4

Approach

  1. Depth is 1 plus the deepest child dictionary’s depth (recursion).

Solution

Python
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.

Advertisement

Learn the concept

New to this topic? Read the lesson, then come back.

More dictionary programs

← All 94 Dictionary Programs