Sub topic 11
Walking data of unknown depth with recursion
Earlier chapters read nested data with chained indexing such as data["a"][1]["b"]. That works when you know the shape in advance. This chapter covers data whose depth you don't know: a comment thread, a menu tree, a parsed JSON response, a configuration file with optional sections. It assumes you can write functions and for loops, know isinstance(), and have seen dict.items() and enumerate().
Why loops are not enough
A nested loop handles a fixed number of levels. A dictionary of dictionaries needs two loops, and one more level needs a third. When the depth varies from one input to the next, you can't write the right number of loops ahead of time.
Recursion fixes this. A recursive function calls itself on the smaller pieces of its input. Nested data has this structure: every list or dictionary contains values, and each of those values is either a leaf (a number, string, None, and so on) or another list or dictionary. One function can handle both cases.
Every recursive function needs two parts:
- Base case: the input needs no further splitting, so the function returns or yields a result directly. Here, the base case is a leaf.
- Recursive case: the input is a container, so the function calls itself on each child.
The basic walker
This is the generator from the chapter plan, shown again with a closer look at each branch.
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',) 3- The
dictbranch loops overitems()and extends the path with the key. - The
listbranch loops withenumerate()and extends the path with the index. - The
elsebranch is the base case. It yields the accumulated path and the leaf. yield frompasses along everything the inner call yields, so the caller sees one flat stream of(path, leaf)pairs.path + (key,)builds a new tuple on each call. Siblings never share a path object, so there is no shared-reference bug of the kind covered earlier.
Strings need no special handling, because the code tests for dict and list only. A string is a sequence, and if you tested for "anything iterable" you would recurse forever, since each character of a string is itself a one-character string.
Because the path is a tuple of keys and indexes, you can use it to read or change the value later:
def get_at(root, path):
for step in path:
root = root[step]
return root
data = {"a": [1, {"b": 2}], "c": 3}
print(get_at(data, ("a", 1, "b"))) # 2Computing a property of the whole structure
Not every recursive function yields. Some combine the results of the recursive calls. This one measures how deeply data is nested:
def depth(value):
if isinstance(value, dict):
children = value.values()
elif isinstance(value, list):
children = value
else:
return 0
return 1 + max((depth(child) for child in children), default=0)
print(depth(5)) # 0
print(depth([])) # 1
print(depth({"a": [1, {"b": 2}], "c": 3})) # 3The container's depth is one more than the deepest child. The default=0 argument matters. Without it, max() of an empty sequence raises ValueError, so an empty list or dictionary would crash the function.
Searching for a key at any depth
Often you know the name of the field you want but not where it sits. This generator finds every value stored under a given key:
def find_all(value, target):
if isinstance(value, dict):
for key, child in value.items():
if key == target:
yield child
yield from find_all(child, target)
elif isinstance(value, list):
for child in value:
yield from find_all(child, target)
tree = {
"id": 1,
"children": [
{"id": 2, "children": [{"id": 3, "children": []}]},
{"id": 4, "children": []},
],
}
print(list(find_all(tree, "id"))) # [1, 2, 3, 4]The function yields a match and then still recurses into it. That way it also finds the target key inside a matching value, if that value is itself a container. Leaves need no branch of their own here: a leaf matches neither if, so the function returns without yielding.
Flattening to dotted paths
Flat key-value pairs are easier to log, compare, or store in a table. This version turns a path into a string such as db.ports[0]:
def flatten(value, prefix=""):
if isinstance(value, dict) and value:
for key, child in value.items():
name = f"{prefix}.{key}" if prefix else str(key)
yield from flatten(child, name)
elif isinstance(value, list) and value:
for index, child in enumerate(value):
yield from flatten(child, f"{prefix}[{index}]")
else:
yield prefix, value
settings = {
"db": {"host": "localhost", "ports": [5432, 5433]},
"debug": False,
"tags": [],
}
for path, leaf in flatten(settings):
print(path, leaf)
# db.host localhost
# db.ports[0] 5432
# db.ports[1] 5433
# debug False
# tags []The conditions isinstance(value, dict) and value differ from the basic walker. An empty container is treated as a leaf, so tags [] appears in the output. The basic walk() yields nothing for an empty container, and the key silently vanishes from the output. Decide which behavior you want, because it changes results such as "how many fields does this record have?"
Transforming without mutating
A recursive function can also return a new structure of the same shape. This one applies a function to every leaf:
def map_leaves(value, func):
if isinstance(value, dict):
return {key: map_leaves(child, func) for key, child in value.items()}
if isinstance(value, list):
return [map_leaves(child, func) for child in value]
return func(value)
prices = {"apple": [1, 2], "box": {"pen": 3}}
print(map_leaves(prices, lambda x: x * 10))
# {'apple': [10, 20], 'box': {'pen': 30}}
print(prices)
# {'apple': [1, 2], 'box': {'pen': 3}}Each level builds a fresh dictionary or list, so the input is never modified and the result shares no containers with it. This gives you a deep-copy-like result without calling copy.deepcopy(). Leaves are passed to func as they are, so if a leaf is a mutable object such as a set, the result still shares it.
Edge cases and failure modes
Other container types
The walkers above recognize only dict and list. Data from other sources may contain tuples, sets, or custom mapping types, and those would be treated as leaves. To include tuples in the list branch, test isinstance(value, (list, tuple)). To accept any dictionary-like object, use collections.abc.Mapping. Sets have no order and no index, so a path through a set has no useful meaning. Treat them as leaves unless you have a reason not to.
The recursion limit
Python limits how deep calls can nest. The default is usually 1000, and sys.getrecursionlimit() reports the current value. Data nested more deeply than that raises RecursionError. Real-world JSON rarely nests more than a few dozen levels, so this mostly matters for hostile input, such as a parsed upload from an untrusted user. Raising the limit with sys.setrecursionlimit() is risky, because a very deep recursion can crash the interpreter itself.
The safer option is an explicit stack, which turns recursion into a loop. This version yields the same pairs as walk():
def walk_iter(root):
stack = [((), root)]
while stack:
path, value = stack.pop()
if isinstance(value, dict):
children = [(path + (k,), v) for k, v in value.items()]
elif isinstance(value, list):
children = [(path + (i,), v) for i, v in enumerate(value)]
else:
yield path, value
continue
stack.extend(reversed(children))
data = {"a": [1, {"b": 2}], "c": 3}
print(list(walk_iter(data)))
# [(('a', 0), 1), (('a', 1, 'b'), 2), (('c',), 3)]The stack holds pairs of path and value still to be visited. The reversed() call matters. A stack pops from the end, so pushing the children in reverse order makes the first child come out first, which preserves the original order. The depth is limited by memory instead of the call stack.
Cycles
A list or dictionary can contain itself:
loop = []
loop.append(loop)
try:
list(walk(loop))
except RecursionError:
print("RecursionError: the structure contains itself")The walker keeps descending into the same list until it hits the recursion limit. Data from json.loads() can't contain cycles, because JSON is a tree. Cycles appear only in structures your own code built, for example a node that stores a reference to its parent. To guard against them, track the id() of every container on the current path:
def walk_safe(value, path=(), ancestors=frozenset()):
if isinstance(value, (dict, list)):
if id(value) in ancestors:
yield path, "<cycle>"
return
ancestors = ancestors | {id(value)}
if isinstance(value, dict):
pairs = value.items()
else:
pairs = enumerate(value)
for key, child in pairs:
yield from walk_safe(child, path + (key,), ancestors)
else:
yield path, value
loop = []
loop.append(loop)
print(list(walk_safe(loop))) # [((0,), '<cycle>')]The set holds only the ancestors of the current value, not every container seen so far. This distinction matters. If one inner list appears twice in a structure without forming a loop (a shared reference), it is a legitimate repeat and should be visited both times. Only a container that contains itself, directly or through its descendants, is a cycle.
Modifying while walking
Don't add or delete keys in a dictionary, or items in a list, while you loop over it. Python raises RuntimeError for a dictionary that changes size during iteration, and a list simply skips items without any error. Changing the value stored under an existing key is safe. For structural edits, collect the paths first, then change the data in a second pass, or build a new structure with a function like map_leaves().
Choosing between the approaches
| Need | Approach |
|---|---|
| Visit every leaf and know where it is | Generator that yields `(path, leaf)` |
| Measure or summarize the whole structure | Function that returns a combined value, like `depth()` |
| Produce a changed copy | Function that returns a new dict or list, like `map_leaves()` |
| Input may be extremely deep or untrusted | Explicit stack with `walk_iter()` |
| Structure may contain cycles | Ancestor tracking as in `walk_safe()` |
If you find yourself writing a different walker for every question about the same data, the structure may have grown too complex for nested dictionaries and lists. The final chapter returns to that decision.
Exercise
Given data = {"a": [], "b": {}}, what does list(walk(data)) return, and what is the smallest change to the else-branch logic that makes both keys appear in the output?
Show answer
It returns an empty list. Both "a" and "b" hold empty containers, so the loops in the dict and list branches never run and nothing is yielded. To make them appear, treat empty containers as leaves: test isinstance(value, dict) and value and isinstance(value, list) and value in the first two branches, as flatten() does. An empty dict or list then falls through to the else branch and is yielded as a leaf, giving [(('a',), []), (('b',), {})].
Exercise
What do depth([]) and depth([[], [[]]]) return with the depth() function from this chapter, and why does the call need default=0?
Show answer
depth([]) returns 1, because an empty list is still one level of container and max() falls back to 0 for its missing children. depth([[], [[]]]) returns 3: the outer list is one level, its deepest child [[]] is two levels (one for itself and one for the empty list inside). Without default=0, max() of an empty generator raises ValueError, so any empty list or dictionary would crash the function.
Exercise
A teammate says walk() is fine for parsing untrusted JSON from users. Name one input that makes it fail and one way to make it safe.
Show answer
A document nested thousands of levels deep, such as "[" repeated 5000 times followed by "]" repeated 5000 times, makes walk() exceed the recursion limit and raise RecursionError. Switching to the explicit-stack walk_iter() removes the call-depth limit. You can also limit the size and nesting of accepted input before walking it.