python合并字典,相同的key的value如何相加 结合函数定义,类,OOP

题目: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
'''

 

  • 0
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Thomas2143

您的打赏是我的动力!!!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值