# 假如 两个字典r1_dic={'a':1,'b':2,'c':3}
r2_dic={'c':4,'d':5}
若两个字典r1_dic和r2_dic有相同的key则对应的value相加,若没有则直接添加过来。结果为dict={'a':1,'b':2,'c':7,'d':5}
方法一
from collections import defaultdict r1_dic={'a':1,'b':2,'c':3} r2_dic={'c':4,'d':5} dic = defaultdict(int) for k,v in r1_dic.items(): dic[k] += v for k,v in r2_dic.items(): dic[k] += v print(dic)
方法二
x={'a':1,'b':2,'c':3} y={'c':4,'d':5} def merge_dict(x,y): for k,v in x.items(): if k in y.keys(): y[k] += v else: y[k] = v
方法三
r1_dic={'a':1,'b':2,'c':3} r2_dic={'c':4,'d':5} from collections import Counter X,Y=Counter(r1_dic),Counter(r2_dic) z=dict(X+Y) print(z)