[英]Flatten nested dictionary into a list of lists
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.这不是我需要的,但我不知道如何解决它。
You can use a recursive generator function:您可以使用递归生成器 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: Output:
[['weather', 'cloudy', 'yes'], ['weather', 'rainy', 'wind', 'strong', 'no'], ['weather', 'rainy', 'wind', 'weak', 'yes'], ['weather', 'sunny', 'humidity', 'high', 'no'], ['weather', 'sunny', 'humidity', 'normal', 'yes']]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.