我有一个代码,结果得到一个像这样的嵌套字典:
{'weather': {'cloudy': 'yes',
'rainy': {'wind': {'strong': 'no', 'weak': 'yes'}},
'sunny': {'humidity': {'high': 'no', 'normal': 'yes'}}}}
现在我需要将其“展平”为这样的列表列表:
[[weather, cloudy, yes], [weather, rainy, wind, strong, no], [weather, rainy, wind, weak, yes], ...]
我尝试了很多不同的方法来解决这个问题,但就是无法解决,有人遇到过类似的问题吗?
编辑:有人要求查看我的一些试验,我尝试通过将其转换为列表来执行类似的操作:
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
返回:
['weather', 'cloudy', 'yes', 'rainy', 'wind', 'strong', 'no', 'weak', 'yes', 'sunny', 'humidity', 'high', 'no', 'normal', 'yes']
这不是我需要的,但我不知道如何解决它。
最佳答案
您可以使用递归生成器函数:
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)))
输出:
[['weather', 'cloudy', 'yes'], ['weather', 'rainy', 'wind', 'strong', 'no'], ['weather', 'rainy', 'wind', 'weak', 'yes'], ['weather', 'sunny', 'humidity', 'high', 'no'], ['weather', 'sunny', 'humidity', 'normal', 'yes']]
关于python - 将嵌套字典展平为列表列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67660551/