【问题标题】:Flatten nested dictionary into a list of lists将嵌套字典展平为列表列表
【发布时间】:2021-05-23 13:58:37
【问题描述】:

我有一个代码,结果是这样的嵌套字典:

{'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']

这不是我需要的,但我不知道如何解决它。

【问题讨论】:

  • 你能展示一些你的试验吗?

标签: python python-3.x dictionary tree


【解决方案1】:

您可以使用递归生成器函数:

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']]

【讨论】:

  • 就是这样!非常感谢。
猜你喜欢
  • 2020-04-01
  • 1970-01-01
  • 2016-06-16
  • 1970-01-01
  • 2013-11-13
  • 1970-01-01
  • 2020-07-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多