python - 将嵌套字典展平为列表列表

标签 python python-3.x dictionary tree

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

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

相关文章:

python-3.x - 如何在 Gunicorn 启动其主进程之前触发函数

c# - Dictionary<Key, Value> 上 .NET 二进制序列化的奇怪行为

python - 如何显示 unicode 字典值

python - 键入多种类型的提示值?

python - 根据字典的键打破字典列表而不丢失顺序

python - 了解 Python 中的闭包作用域

python - Django/WeasyPrint : Bangla Font Rendering Issue

Windows 上的 Python os.path.join

Python MySQL UTF-8 编码因执行顺序而异

python-3.x - 无法使用 .json key 文件创建 Pub/Sub Publisher 客户端