假设我有两本词典:

x={a: 4, is: 3, the :5}
y={i: 5, a:1, is:2, the: 1}

我想要结果:

z={a:5, is:5, the: 6, i:5}

我用了dict3 = {**dict1, **dict2}本,但它似乎覆盖了另一本词典,而不是把它们加起来.

d3=dict()
print("Merge dic")
d3== {**dict1, **dict2}
for key in list(d3.keys()):
    print(key, ":", d3[key])

推荐答案

您可以直接添加Counter

>>> from collections import Counter
>>> x={'a': 4, 'is': 3, 'the' :5} 
>>> y={'i': 5, 'a':1, 'is':2, 'the': 1}
>>> Counter(x) + Counter(y)
Counter({'the': 6, 'a': 5, 'is': 5, 'i': 5})
>>> dict(Counter(x) + Counter(y))
{'a': 5, 'is': 5, 'the': 6, 'i': 5}

Python相关问答推荐

除了Python之外,可以替代bare?

按 struct 值对Polars列表[struct[]]排序

为什么基于条件的过滤会导致pandas中的空数据框架?

PyQt5如何将pyuic 5生成的Python类添加到QStackedWidget中?

从管道将Python应用程序部署到Azure Web应用程序,不包括需求包

如何使用stride_tricks.as_strided逆转NumPy数组

将轨迹优化问题描述为NLP.如何用Gekko解决这个问题?当前面临异常:@错误:最大方程长度错误

如何处理嵌套的SON?

配置Sweetviz以分析对象类型列,而无需转换

Pandas 在最近的日期合并,考虑到破产

如何根据参数推断对象的返回类型?

在Python Attrs包中,如何在field_Transformer函数中添加字段?

计算组中唯一值的数量

为什么以这种方式调用pd.ExcelWriter会创建无效的文件格式或扩展名?

我对我应该做什么以及我如何做感到困惑'

用砂箱开发Web统计分析

Python列表不会在条件while循环中正确随机化'

如何更新pandas DataFrame上列标题的de值?

Django—cte给出:QuerySet对象没有属性with_cte''''

如何在PySide/Qt QColumbnView中删除列