如何在Python3中将这个嵌套字典转换成一个单独的字典?

2024-04-26 00:56:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一本这样的字典:

a = {"a": "b", "c": "d", {"e": "E", "f": "F"}}

我想把它转换成:

b = {"a": "b", "c": "d", "e": "E", "f": "F"}

Tags: 字典
2条回答

首先,dict无效,它应该始终是一个键值对。下面是你的字典应该是什么样的情况

a = {"a": "b", "c": "d", 'something':{"e": "E", "f": "F"}}

def func(dic):
    re ={}
    for k,v in dic.items():
        if isinstance(v, dict):
            re.update(v)
        else:
            re.update({k:v})
    return re

print(func(a))

输出

 {'a': 'b', 'c': 'd', 'e': 'E', 'f': 'F'}

如果你对丢失你的内在格言所属的钥匙感到满意(你没有指定如何处理它), 我会递归地做:

def unnest_dict(d):
    result = {}
    for k,v in d.items():
        if isinstance(v, dict):
            result.update(unnest_dict(v))
        else:
            result[k] = v
    return result
unnest_dict({"a": "b", "c": "d", "something":{"e": "E", "f": "F"}})

{'a':'b','c':'d','e':'e','f':'f'}

相关问题 更多 >