I have a structure consisting of nested lists and dicts. I want to apply a function to every element. How to do it without recursion.
def visit(data, func):
if isinstance(data, dict):
for k, v in data.items():
data[k] = visit(v, func)
return data
elif isinstance(data, list):
for i, v in enumerate(data):
data[i] = visit(v, func)
return data
else:
return func(data)
The recursive version works for small data, but I hit the RecursionError exception when the data is big.
I looked for general ways to eliminate recursion, the ones I found rely on first transforming the recursive call to a tail call, my problem with this is the recursive call in my example is inside a loop.