sum list of dictionary values

后端 未结 7 2237
情深已故
情深已故 2020-12-20 21:23

I have a list of dictionary in this form :

[
{\'signal_8\': 1, \'signal_1\': 7, \'signal_10\': 5, \'signal_5\': 2, \'signal_2\': 5, \'signal_6\': 3, \'signa         


        
7条回答
  •  春和景丽
    2020-12-20 22:26

    Can you try below code

    basedict=siglist[0]
    for k in basedict.keys():
        result=[currdict[k] for currdict in siglist]
        endval=sum(result)
        print("Key %s and sum of values %d"%(k,endval))
    

    Output

    Key signal_9 and sum of values 12
    Key signal_2 and sum of values 15
    Key signal_8 and sum of values 3
    Key signal_5 and sum of values 6
    Key signal_7 and sum of values 24
    Key signal_10 and sum of values 15
    Key signal_1 and sum of values 21
    Key signal_6 and sum of values 9
    Key signal_4 and sum of values 27
    Key signal_3 and sum of values 18
    

    Note :- As we are sure that all keys in all dictionaries are same this solution works well. If you have a dictionary with non matching elements then it would result in KeyError . So be aware of that limitation

提交回复
热议问题