How to flatten disorganised dictionaries into list?

Code Monkey :

I attempted to flatten a disorganized dictionary (that in turn was taken from a json file) to ease extracting info. Below is an example of how the dictionary is structured and my attempt at flattening it:

data = {'horse':{'speed':{"walk": 40, "run":50}}, 'dog':{'run':30}, 'human':{'gait':{'normal':{'run': 25, 'walk': 30}}}}

flat_dict = []
for items in list(data.items()):
    flat_list = []
    flat_list.append(items[0])
    try:
        for item in list(items[1].items())[0]:
            if type(item) is not dict: 
                flat_list.append(item)
            else:
                flat_list.append(list(item.keys())[0])
                flat_list.append(list(item.values())[0])
    except:
        flat_list.append(items[0])
    flat_dict.append(flat_list)

print(flat_dict)

However the above code does not flatten the entire dictionary and some information is lost, here's the output of the above code:

[['horse', 'speed', 'walk', 40], ['dog', 'run', 30], ['human', 'gait', 'normal', {'run': 25, 'walk': 30}]]

What I wanted was:

[['horse', 'speed', 'walk', 40, 'run', 50], ['dog', 'run', 30], ['human', 'gait', 'normal', 'run', 25, 'walk', 30]]

What do I do?

kederrac :

you can use a recursive approach with a list comprehension:

 def gen(d):
    if isinstance(d, dict):
        for k, v in d.items():
            yield k
            yield from gen(v)
    else:
        yield d 

[[k, *gen(v)] for k, v in data.items()]

output:

 [['horse', 'speed', 'walk', 40, 'run', 50],
 ['dog', 'run', 30],
 ['human', 'gait', 'normal', 'run', 25, 'walk', 30]]

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=31762&siteId=1