sum list of dictionary values

后端 未结 7 2272
情深已故
情深已故 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:07

    Your current code uses one accumulating sum for all the signals, when instead you need a seperate the sum for each signal.

    If you want your original code to work, you need to first check if the key exists in result, and initialise it 0 beforehand if it isn't. Then accumulate the sum for the respective key.

    Code:

    result = {}
    for elm in original_list:
        for k, v in elm.items():
    
            # Initialise it if it doesn't exist
            if k not in result:
                result[k] = 0
    
            # accumulate sum seperately 
            result[k] += v
    
    print(result)
    

    Output:

    {'signal_9': 12, 'signal_8': 3, 'signal_1': 21, 'signal_3': 18, 'signal_2': 15, 'signal_5': 6, 'signal_4': 27, 'signal_7': 24, 'signal_6': 9, 'signal_10': 15}
    

    Note: As others have shown, to avoid initialising yourself, you can use collections.defaultdict() or collections.Counter() instead.

提交回复
热议问题