Sub topic 11
Walking data of unknown depth with recursion
This chapter assumes you can write functions, loop over lists and dictionaries, and read nested data with chained indexing. It also assumes you know that json.loads() returns nested dictionaries and lists. The chapter shows how to visit every value in a structure when you don't know in advance how deep it goes.
Why nested loops stop working
A nested loop handles one level per for. That works when you know the shape, such as a dictionary of dictionaries. It fails when the depth varies. JSON from a web service, a configuration tree, or a folder listing can nest to any depth, and you can't write a fixed number of loops for it.
Recursion solves this. A recursive function calls itself on each child of the current value. The structure's own nesting then decides how many calls happen.
The two parts of a recursive walk
Every walk has two kinds of case:
- Container case. The value is a
dictor alist. Call the function again on each child. - Leaf case. The value is anything else, such as a number, string, boolean, or
None. Report it and stop.
The leaf case is the base case. Without it, the function would never stop calling itself.
A generator that reports paths
The function below yields every leaf together with its path, which is the tuple of keys and indexes that leads to it.
def walk(value, path=()):
if isinstance(value, dict):
for key, child in value.items():
yield from walk(child, path + (key,))
elif isinstance(value, list):
for index, child in enumerate(value):
yield from walk(child, path + (index,))
else:
yield path, value
data = {"a": [1, {"b": 2}], "c": 3}
for path, leaf in walk(data):
print(path, leaf)
# ('a', 0) 1
# ('a', 1, 'b') 2
# ('c',) 3Points to notice:
path + (key,)builds a new tuple on each call. The parent's path is never changed, so sibling branches can't interfere with each other.yield frompasses every result from the inner call up to the caller. Without it, the results of the recursive calls would be thrown away.enumerate()supplies the index for lists, anditems()supplies the key for dictionaries.- Each path is a valid sequence of lookups. You can follow it with
data["a"][1]["b"].
Using the walker
Because walk() is a generator, it produces values one at a time. You can feed it to any tool that accepts an iterable.
def walk(value, path=()):
if isinstance(value, dict):
for key, child in value.items():
yield from walk(child, path + (key,))
elif isinstance(value, list):
for index, child in enumerate(value):
yield from walk(child, path + (index,))
else:
yield path, value
data = {"a": [1, {"b": 2}], "c": 3, "d": [4, 5]}
total = sum(leaf for _, leaf in walk(data))
print(total) # 15
deep = [path for path, _ in walk(data) if len(path) > 2]
print(deep) # [('a', 1, 'b')]The first query adds every number in the structure. The second finds leaves buried more than two levels down. Neither query needed to know the shape of data.
Common errors
- Forgetting the leaf case. A function that only handles
dictandlistreturns nothing for plain values, so leaves go missing. - Dropping
yield from. Callingwalk(child)withoutyield fromcreates a generator and discards it. The output is silently empty or incomplete. - Mutable path arguments. A default of
path=[]is shared between calls. Use a tuple, as above, or copy the list before extending it. - Other container types.
isinstance(value, dict)skips tuples and sets. Add them to the checks if your data contains them. JSON never produces them. - Very deep data. Python limits recursion to about 1000 calls by default (
sys.getrecursionlimit()). Data nested deeper than that raisesRecursionError. Real-world JSON rarely comes close. For extreme depth, use an explicit stack with a loop instead. - Cycles. A structure that contains itself, for example
a = []; a.append(a), recurses until it hits the limit. JSON can't contain cycles, but structures built in code can.
Exercises
Exercise
Write a function max_depth(value) that returns how many levels of dict or list nesting a value has. A plain value such as 5 has depth 0, and {"a": [1]} has depth 2. Treat an empty dict or list as depth 1.
Show answer
def maxdepth(value):
if isinstance(value, dict):
children = value.values()
elif isinstance(value, list):
children = value
else:
return 0
return 1 + max((maxdepth(child) for child in children), default=0)
print(maxdepth(5)) # 0
print(maxdepth({"a": [1]})) # 2
print(max_depth([])) # 1
The leaf case returns 0. For a container, the function adds 1 to the deepest child. The default=0 argument stops max() from failing on an empty container.
Exercise
The walk() generator yields (path, leaf) pairs. Why does it use path + (key,) instead of appending to a shared list?
Show answer
Concatenation creates a new tuple for each call, so each branch has its own path. A shared list would be changed by every call, and the paths yielded for earlier leaves would be corrupted or mixed up with those of later leaves.