Skip to content

Python dictionary sum values with the same key | Example code

A list of dictionaries can have the same key with different or same values. Using reduce() function and + operator can sum values with the same key in the Python dictionary.

You can’t have the same key twice in the Python dictionary. Every key in the dictionary must be unique. Read the documentation. (If a key occurs more than once, the last value for that key becomes the corresponding value in the new dictionary.)

Python dictionary sum values with the same key example

Simple example code.

For this example, you have to import the functools module.

import collections
import functools
import operator

my_dict = [{'a': 5, 'b': 1, 'c': 2},
           {'a': 2, 'b': 5},
           {'a': 10, 'c': 10}]

# sum the values with same keys
res = dict(functools.reduce(operator.add,
                            map(collections.Counter, my_dict)))

print("New dict : ", res)

Output:

Python dictionary sum values with the same key

Or use the counter method

import collections

my_dict = [{'a': 5, 'b': 1, 'c': 2},
           {'a': 2, 'b': 5},
           {'a': 10, 'c': 10}]

counter = collections.Counter()
for d in my_dict:
    counter.update(d)

res = dict(counter)

print("New dict : ", res)

Output: New dict : {‘a’: 17, ‘b’: 6, ‘c’: 12}

Comment if you have any doubts or suggestions on this Python sum dictionary code.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

2 thoughts on “Python dictionary sum values with the same key | Example code”

  1. please how then do u add same key values from different dictionaries for example
    ang={“water”:10,”b”:2,”C”:3}
    bag={“water”:5,”b”:6,”c”:5}
    result={“water”:15,”b”:8,”c”:8}

  2. The code seems to fail with negative numbers. For example, if I change the first entry to a=-5:
    my_dict = [{‘a’: -5, ‘b’: 1, ‘c’: 2},
    {‘a’: 2, ‘b’: 5},
    {‘a’: 10, ‘c’: 10}]
    ~[…first example code…]~
    This is the output:
    New dict : {‘b’: 6, ‘c’: 12, ‘a’: 10}

    The second example code appears to work correctly.

Leave a Reply

Your email address will not be published. Required fields are marked *