从嵌套字典的底层创建字典的Pythonic方法
我有一个包含嵌套字典的字典,如下所示:从嵌套字典的底层创建字典的Pythonic方法,python,dictionary,Python,Dictionary,我有一个包含嵌套字典的字典,如下所示: example_dict = { "test1": "string here", "test2": "another string", "test3": { "test4": 25, "test5": {
example_dict = {
"test1": "string here",
"test2": "another string",
"test3": {
"test4": 25,
"test5": {
"test7": "very nested."
},
"test6": "yep, another string"
},
}
假设嵌套在其中的所有键都是唯一的,是否有一种Pythonic方法来获取此字典并获得“底部”级别的键和值
我的意思是递归地进入字典并获取所有键:值对,其中值不是字典(但仍然捕获满足标准的键:值对)?因此,对于上述内容,将返回以下内容:
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)
通过一点递归,它的实现相当简单:
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)
我明白了,在函数中引用函数的逻辑是我所缺少的。谢谢。我明白了,在函数中引用函数的逻辑是我所缺少的。谢谢