'Recursive function without return statement

I have some data that is inserted into a nested dictionary. The data are created and could theoretically be endlessly deep. It could e.g. looks like this:

data = {'leaves': {'dark': {}, 'green': {'light': {}}, 'without': {'veins': {'blue': {}}}, '5': {}}}

For some clarification: In this small sample, it means that a certain plant has 'leaves', the 'leaves' are 'dark', 'green' and 'without'. The 'green' is 'light' in this example etc.

I want to unnest this dictionary and store every key, value combination into a tuple. That could for example look like this:

[('leaves', 'dark'), ('leaves', 'green'), ('green', 'light'), ('without', 'veins'), ('leaves', '5'), ('veines', 'blue')]

Note: order is not important. For those interested, these tuples are further manipulated and will end up in a knowledge graph.

I thought a recursive function would do the trick here, but my function works best without the restatement, a function without a return statement is just a simple loop. However, I cannot make it work with a simple loop.

edit: the doubles variable is a global list.

The function I wrote:

def undict(d):
    for key in d.keys():
        if isinstance(d[key], dict):
            doubles += [(key, k) for k in d[key].keys()]
        undict(d[key]) # Normally: return undict(d[key])

Maybe can anyone offer some insights on how to make it truly recursive or use a simple loop? I am lost at this point.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source