python合并多个dict---合并多个字典值---字典值相加
文章目录
- 序
- 多个dict同key值相加
- collection.Counter
- 传参
- 重载+号
- 多个dict合并
- 练习
序
主要是借助Counter、函数传参和+运算符重载!各有优劣!
多个dict同key值相加
collection.Counter
借助collections.Counter,但是它只适用于值为整数或者小数类型**,否则报错!**
from collections import Counter
a = {"1":2}
b = {"1":30}
print(dict(Counter(a)+Counter(b)))a = {"1":2.0}
b = {"1":30.5}
print(dict(Counter(a)+Counter(b)))

传参
借助函数传参,但是不能同key相加。如下:
a = {"1":2}
b = {"2":3}def merge_dicts(**kwargs):return kwargsmerge_dicts(**a, **b)

重载+号
写代码多。
from collections.abc import Iterableclass MyDict:def __init__(self, dic):self._dic = dicdef __add__(self, other):new_dic = self._dicfor k, v in other._dic.items():if k in new_dic:if isinstance(v, Iterable) or isinstance(v, int) or isinstance(v, float):new_dic[k] += velse:new_dic[k] = vself._dic = new_dicreturn self._dica = MyDict({1: "11a"})
b = MyDict({10: 21, 1: "11b"})
a+b

多个dict合并
两种方法
# 方法一, 借助函数传参
a = {"1":2}
b = {"2":3}def update(**kwargs):return kwargsupdate(**a, **b)
输出如下:

# 方法二
from collections import Counter
a = {"1":2}
b = {"2":3}
dict(Counter(a)+Counter(b))

练习
请您对以上三种方法的弊端进行复现。