我有一个包含嵌套字典的字典,如下所示:
example_dict = {
"test1": "string here",
"test2": "another string",
"test3": {
"test4": 25,
"test5": {
"test7": "very nested."
},
"test6": "yep, another string"
},
}
假设所有嵌套在其中的键都是唯一的,是否有一种Pythonic方法来获取这个字典并获得一个“底层”键和值?
通过这个我的意思是递归到字典并获得所有键:值对,其中值不是字典(但仍然捕获键:在其中的值对完成critera)?因此,对于上述内容,将返回以下内容:
resulting_dict = {
"test1": "string here",
"test2": "another string",
"test4": 25,
"test7": "very nested.",
"test6": "yep, another string"
}
答案 0 :(得分:5)
通过一点递归,它很简单:
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)