pythonは辞書を合併して、同じkeyのvalueはどのように結合関数の定義を加算して、クラス、OOP

2123 ワード

テーマ: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
'''