I'm trying to figure out how to map a recursive structure containing both dictionaries and lists, so far I've got this:
import collections
def rec_walk(l):
for v in l:
if isinstance(v, list):
yield from rec_walk(v)
else:
yield v
def rec_map(l, f):
for v in l:
if isinstance(v, collections.Iterable):
if isinstance(v, list):
yield list(rec_map(v, f))
elif isinstance(v, dict):
yield dict(rec_map(v, f))
else:
yield f(v)
a = ["0", ["1", "2", ["3", "4"]], [[[[["5"]]]]]]
print(list(rec_map(a, lambda x: x + "_tweaked")))
b = {
'a': ["0", "1"],
'b': [[[[[["2"]]]]]],
'c': {
'd': [{
'e': [[[[[[["3"]]]]]]]
}]
}
}
print(dict(rec_map(b, lambda x: x + "_tweaked")))
Output:
[[[]], [[[[[]]]]]]
{}
As you can see, problem with the above example is that rec_map is not returning a properly mapped structure, what I'm trying to get is either the same structure mapped properly or a new cloned mapped one, for example, something like this:
a = ["0", ["1", "2", ["3", "4"]], [[[[["5"]]]]]]
rec_map(a, lambda x: x + "_tweaked")
should transform a
into:
["0_tweaked", ["1_tweaked", "2_tweaked", ["3_tweaked", "4_tweaked"]], [[[[["5_tweaked"]]]]]]
and:
b = {
'a': ["0", "1"],
'b': [[[[[["2"]]]]]],
'c': {
'd': [{
'e': [[[[[[["3"]]]]]]]
}]
}
}
print(dict(rec_map(b, lambda x: x + "_tweaked")))
into:
b = {
'a': ["0_tweaked", "1_tweaked"],
'b': [[[[[["2_tweaked"]]]]]],
'c': {
'd': [{
'e': [[[[[[["3_tweaked"]]]]]]]
}]
}
}