繁体   English   中英

从嵌套字典的最底层创建字典的Python方式

[英]Pythonic way to create dictionary from bottom level of nested dictionary

我有一本包含嵌套字典的字典,如下所示:

example_dict = {
                "test1": "string here",
                "test2": "another string",
                "test3": {
                        "test4": 25,
                        "test5": {
                                  "test7": "very nested."
                        },
                        "test6": "yep, another string"
                },
}

假设嵌套在其中的所有键都是唯一的,是否有Python方式可以使用此字典并获得键和值的“最低”级别?

我的意思是说要递归进入字典并获取所有值不是字典的key:value对(但仍捕获满足该条件的key:value对)? 因此,对于以上内容,将返回以下内容:

resulting_dict = {
                "test1": "string here",
                "test2": "another string",
                "test4": 25,
                "test7": "very nested.",
                "test6": "yep, another string"
}

进行一点递归就很简单了:

example_dict = {
    "test1": "string here",
    "test2": "another string",
    "test3": {
        "test4": 25,
        "test5": {
            "test7": "very nested."
        },
        "test6": "yep, another string"
    },
}


def flatten(dictionary):
    output = dict()
    for k, v in dictionary.items():
        if isinstance(v, dict):
            output.update(flatten(v))
        else:
            output[k] = v

    return output

resulting_dict = flatten(example_dict)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM