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
- Non-dicts and empty dicts have depth zero.
- Otherwise it recurses into every child value.
- Depth is one more than the deepest child's.
Keywords and builtins used here
defdepthdictforifisinstancemaxreturn
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.
Step 5 of 5 in Algorithms, step 55 of 72 in Language basics.