Python sum dict values based on keys

后端 未结 3 1594
遥遥无期
遥遥无期 2021-01-15 14:11

How to sum values from dict where values are string. I mean how to sum values where multiply key is same in dictionary.

dict

values = [
    {
                


        
3条回答
  •  滥情空心
    2021-01-15 14:44

    This is a simple and specific solution, I am sure there are more general and cleverer ones. :)

    from collections import defaultdict
    
    pr = defaultdict(float)
    ra = defaultdict(float)
    for el in values:
        combi = (el['prod_name'], el['prod_hola'])
        pr[combi] += el['prihod']
        ra[combi] += el['rashod']
    
    results = [dict(rashod=r, prihod=p, \
                    prod_name=nh[0], prod_hola=nh[1]) \
               for r,p,nh in zip(ra.values(), pr.values(), pr)]
    print results
    

    gives

    [{'rashod': 0.0, 'prihod': 100.0, 'prod_name': 'c', 'prod_hola': 'f'},
     {'rashod': 0.0, 'prihod': 1500.0, 'prod_name': 'a', 'prod_hola': 'b'},
     {'rashod': 0.0, 'prihod': 460.0, 'prod_name': 'r', 'prod_hola': 't'}]
    

提交回复
热议问题