假设有 2 个字典:
A = {'a':1, 'b':2, 'c':3}
B = {'c':2, 'd':2, 'e':4}
如何将它们合并在一起以获得:
C = {'a':1, 'b':2, 'c':5, 'd':2, 'e':4}
我知道A.update(B)
会给我一个合并的字典,但我想要的 A 中“c”的值将被 B 中“c”保存的值覆盖,而不是被添加。
最佳答案
也许最简单的方法是使用 Counter
:
from collections import Counter
A = {'a':1,'b':2,'c':3}
B = {'c':2,'d':2,'e':4}
C = dict(Counter(A) + Counter(B))
print(C)
# {'a': 1, 'b': 2, 'c': 5, 'd': 2, 'e': 4}
关于python - 如何合并两个Python字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43702626/