本文介绍了如何在类似的键上合并任意深度的多个嵌套字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个词典列表,其中一些词典在1级和2级共享相同的密钥,有些词典在1级共享相同的密钥,有些则不共享密钥.我想从顶层开始将字典合并在一起.
I have a list of dictionaries, some of which share the same key at levels 1 and 2, some share the same key just a level 1, some don't share a key. I want to merge the dictionaries together starting from the top level.
input = [
d1 = {'a' : {'az' : {'a1': 2}}}
d2 = {'a' : {'az' : {'g' : 9}}}
d3 = {'a' : {'aa' : {'g' : 9}}}
d4 = {'b' : {'az' : {'g' : 9}}}
]
result = [
{'a': {'az' : {'a1' : 2, 'g' : 9}, {'aa' : {'g' : 9}}}
{'b' : {'az' : {'g' : 9}}}
]
推荐答案
最简单的方法是递归合并字典,请参见下面的示例.
The easiest approach would be to recursively merge the dictionaries, see sample below.
# https://gist.github.com/angstwad/bf22d1822c38a92ec0a9
def merge(A, B):
for k, v in B.items():
if k in A and isinstance(A[k], dict) and isinstance(v, dict):
merge(A[k], v)
else:
A[k] = v
input_dicts = [
{'a' : {'az' : {'a1': 2}}},
{'a' : {'az' : {'g' : 9}}},
{'a' : {'aa' : {'g' : 9}}},
{'b' : {'az' : {'g' : 9}}}
]
result = {}
for d in input_dicts:
merge(result, d)
这篇关于如何在类似的键上合并任意深度的多个嵌套字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!