typestar

Depth of a nested dict in Python

Measuring recursion depth on nested data.

def depth(tree):
    if not isinstance(tree, dict) or not tree:
        return 0
    return 1 + max(depth(child) for child in tree.values())

How it works

  1. Non-dicts and empty dicts have depth zero.
  2. Otherwise it recurses into every child value.
  3. Depth is one more than the deepest child's.

Keywords and builtins used here

The run, in numbers

Lines
4
Characters to type
124
Tokens
38
Three-star pace
100 tpm

At the three-star pace of 100 tokens a minute, this run takes about 23 seconds.

Type this snippet

Step 5 of 5 in Algorithms, step 55 of 72 in Language basics.

← Previous Next →