需要对不确定长度的字典和不确定个数的字典做相加操作,相同的key的value相加,
from collections import OrderedDict,Counter dict1 = {1:2,3:4} dict2 = {1:2,3:4,8:90} dict3 = {1:2,3:4,8:9,10:89} result = Counter({}) dict_list = [dict1,dict2,dict3]#这里字典随便搞 for dicts in dict_list: result= result +Counter(dicts) last_result = dict(result) 基于类的实现 class AddTest(object): '''两个字典相加的类,返回一个字典''' def __init__(self,a): self.a=a assert isinstance(a,dict) def __str__(self): return self.a def __add__(self, other): for i in self.a.keys(): if other.a.get(i): self.a[i] = self.a.get(i) +other.a.get(i) for i in other.a.keys(): if not self.a.get(i): self.a[i] = other.a.get(i) return self.a __repr__ = __str__ a={"a":1,"b":2,"d":10} b={"c":1,"a":2,"d":5} c = AddTest(a)+AddTest(b) print c,type(c) 或者 a={"a":1,"b":2,"d":10} b={"e":1,"f":2,"n":5} c={"c":3} test_list =[a,b,c] result = {} for i in test_list: result=AddTest(i) +AddTest(result) print result