Flatten nested dictionary into a list of lists

Viewed 163

I have a code that as a result gets a nested dictionary like this:

{'weather': {'cloudy': 'yes',
         'rainy': {'wind': {'strong': 'no', 'weak': 'yes'}},
         'sunny': {'humidity': {'high': 'no', 'normal': 'yes'}}}}

now I need to "flatten" that to a list of list like this:

[[weather, cloudy, yes], [weather, rainy, wind, strong, no], [weather, rainy, wind, weak, yes], ...]

I've tried many different ways to approach this but just can't get it right, did anyone come across a similar issue?

Edit: someone has requested to see some of my trials, I've tried doing it something like this by turning it into a list:

def change(self, tree):
    l = []
    for key, value in tree.items():
        l.append(key)
        if type(value) is dict:
            l.extend(change(value))
        else:
            l.append(value)

    return l

this returns:

['weather', 'cloudy', 'yes', 'rainy', 'wind', 'strong', 'no', 'weak', 'yes', 'sunny', 'humidity', 'high', 'no', 'normal', 'yes']

which is not what I need but I'm not sure how to fix it.

1 Answers

You can use a recursive generator function:

d = {'weather': {'cloudy': 'yes', 'rainy': {'wind': {'strong': 'no', 'weak': 'yes'}}, 'sunny': {'humidity': {'high': 'no', 'normal': 'yes'}}}}
def flatten(d, c = []):
   for a, b in d.items():
      yield from ([c+[a, b]] if not isinstance(b, dict) else flatten(b, c+[a]))

print(list(flatten(d)))

Output:

[['weather', 'cloudy', 'yes'], ['weather', 'rainy', 'wind', 'strong', 'no'], ['weather', 'rainy', 'wind', 'weak', 'yes'], ['weather', 'sunny', 'humidity', 'high', 'no'], ['weather', 'sunny', 'humidity', 'normal', 'yes']]
Related