python - 如何合并两个Python字典?

标签 python dictionary

假设有 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/

相关文章:

python - 无法在Python中安装Tensorflow

python - 如果 slug 已经存在于 postgresql 数据库中,则跳过保存行 - python

python - 什么时候用类,什么时候用字典?

python - 在元组字典中搜索多个最小值

c# - Dictionary 如何从海量数据中查找特定的键值?

python - 查找一行下一行

python - 有没有办法使用 JS 回调从 bokeh (python) 更新选择菜单中的选项?

python - 多分支逻辑的标记用法

c++ - c++中的fstream指针映射

c++ - C++ 中的 std::map<key, data> 是否支持结构等 native 数据类型?