Skip to content

Python dictionary sum values with the same key | Example code

  • by

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 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 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}

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

Note: IDE: PyCharm 2021.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.

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.