Recursion always updates the dictionary

Viewed 116
def recursion(input_type):
    print('input_type ',input_type)
    if isinstance(input_type, dict):
        num = 0
        for k,v in input_type.items():
            if isinstance(v, dict):
                print('from recursion')
                recursion(v)
            elif isinstance(v, list):
                for j in v:
                    if isinstance(j, dict):
                        print('from recursion level 2')
                        recursion(j)
            else:
                temp_dict = {k:v}   
                print('type: ',type(temp_dict), k, v)
            print('num',num)
            num = num+1  

for i in list_:
    recursion(i)     

How to get the interim results from the recursion.

consider the input as shown below:

input: [{'a':a, 'b':b, 'c':[{'d':d, 'e':e}]}]
Updated input: [ {'a':a, 'b':b, 'c': { 'd':d, 'e': [ {'f':f, 'g':g}, {'f':f1, 'g':g1} ] } } ]

desired output: [{'a':a, 'b':b, 'd':d, 'f':f, 'g':g, 'f_new':f1, 'g_new':g1}]

If the key is duplicate then it should update such as 'f' to 'f_new' or something like that

Thank you in advance!!

1 Answers

You can iterate over the dict items and if an item is a list, recursively flatten the dicts within it:

def f(o):
    return {a: b for k, v in o.items() for a, b in ((i for d in (v if isinstance(v, list)
        else (v,)) for i in f(d).items()) if isinstance(v, (list, dict)) else ((k, v),))}

so that given:

lst = [{'a': 'a', 'b': 'b', 'c': [{'d': 'd', 'e': 'e'}, {'f': [{'g': 'g'}]}]}]

[f(d) for d in lst] would return:

[{'a': 'a', 'b': 'b', 'd': 'd', 'e': 'e', 'g': 'g'}]

and that given:

lst = [{'a': 'a', 'b': 'b', 'c': {'d': 'd', 'e': {'f': 'f', 'g': 'g'}}}]

[f(d) for d in lst] would return:

[{'a': 'a', 'b': 'b', 'd': 'd', 'f': 'f', 'g': 'g'}]

To avoid collisions in merged keys, append _new to a duplicating key until it is found not pre-existing, in which case you cannot use comprehension:

def f(o):
    output = {}
    for k, v in o.items():
        for a, b in ((i for d in (v if isinstance(v, list) else (v,)) for i in f(d).items())
                if isinstance(v, (list, dict)) else ((k, v),)):
            while a in output:
                a += '_new'
            output[a] = b
    return output

so that given:

lst = [{'a': 'a', 'b': 'b', 'c': {'d': 'd', 'e': [{'f': 'f', 'g': 'g'}, {'f': 'f1', 'g': 'g1'}]}}]

[f(d) for d in lst] would return:

[{'a': 'a', 'b': 'b', 'd': 'd', 'f': 'f', 'g': 'g', 'f_new': 'f1', 'g_new': 'g1'}]

Demo: https://repl.it/@blhsing/NonstopSeveralActionscript

Related