题目:python合并字典,相同的key的value如何相加?
x = {'apple':1,'banana':2}
y = {'banana':10,'pear':11}
解:(如果字典存在不是字符串的key,把文中的所有的f-string直接替换为变量名)
'''
0 题目:python合并字典,相同的key的value如何相加
1 使用函数实现,结合reduce函数实现多个相加
2 使用类实现加号对不限制个数的字典相加
'''
'''
1 方法单个相加实现
'''
x = {'apple':1,'banana':2}
y = {'banana':10,'pear':11}
def func(dict1,dict2):
for i,j in dict2.items():
if i in dict1.keys():
dict1[i] += j
else:
dict1.update({f'{i}' : dict2[i]})
return dict1
print(func(x,y))
'''
1 方法多个相加的实现
'''
from functools import reduce
x = {'apple':1,'banana':2}
y = {'banana':10,'pear':11}
z = {'pear':5,'tudou':22}
def func(dict1,dict2):
for i,j in dict2.items():
if i in dict1.keys():
dict1[i] += j
else:
dict1.update({f'{i}' : dict2[i]})
return dict1
print(reduce(func,[x,y,z]))
'''
使用面向对象来实现多个相加
'''
x = {'apple':1,'banana':2}
y = {'banana':10,'pear':11}
z = {'pear':5,'tudou':22}
class Fruit(object):
def __init__(self,kwargs):
dict1 = kwargs
self.mydict = kwargs
for i , j in kwargs.items():
# self.i = j #返回self.2 = 10 ;此语句无法成功赋值,故隐藏
setattr(self,i,j) #其实就是考察setattr函数知不知道
def __add__(self, other):
for m , n in other.mydict.items():
if m in self.mydict.keys():
self.mydict[m] += n
else:
self.mydict.update({f'{m}' : other.mydict[m]})
result = self.mydict
return Fruit(result)
if __name__ == '__main__':
x = Fruit(x) + Fruit(y) + Fruit(z)
print(x.mydict)
print(x.banana)
'''
结果:
{'apple': 1, 'banana': 12, 'pear': 16, 'tudou': 22}
12
'''