Open In App

Python | Sum list of dictionaries with same key

You have given a list of dictionaries, the task is to return a single dictionary with sum values with the same key. Let’s discuss different methods to do the task. 

Method #1: Using reduce() + operator

Step-by-step approach:



Below is the implementation of the above approach:




# Python code to demonstrate
# return the sum of values of dictionary
# with same keys in list of dictionary
 
import collections, functools, operator
 
# Initialising list of dictionary
ini_dict = [{'a':5, 'b':10, 'c':90},
            {'a':45, 'b':78},
            {'a':90, 'c':10}]
 
 
# printing initial dictionary
print ("initial dictionary", str(ini_dict))
 
# sum the values with same keys
result = dict(functools.reduce(operator.add,
         map(collections.Counter, ini_dict)))
 
print("resultant dictionary : ", str(result))

Output:

initial dictionary [{‘b’: 10, ‘a’: 5, ‘c’: 90}, {‘b’: 78, ‘a’: 45}, {‘a’: 90, ‘c’: 10}] resultant dictionary : {‘b’: 88, ‘a’: 140, ‘c’: 100}

Time Complexity: O(n)
Auxiliary Space: O(1)

Method #2: Using counter

Step-by-step approach:

Below is the implementation of the above approach:




# Python code to demonstrate
# return the sum of values of dictionary
# with same keys in list of dictionary
 
import collections
 
# Initialising list of dictionary
ini_dict = [{'a':5, 'b':10, 'c':90},
            {'a':45, 'b':78},
            {'a':90, 'c':10}]
 
# printing initial dictionary
print ("initial dictionary", str(ini_dict))
 
# sum the values with same keys
counter = collections.Counter()
for d in ini_dict:
    counter.update(d)
     
result = dict(counter)
 
 
print("resultant dictionary : ", str(counter))

Output:

initial dictionary [{‘c’: 90, ‘a’: 5, ‘b’: 10}, {‘a’: 45, ‘b’: 78}, {‘a’: 90, ‘c’: 10}] resultant dictionary : Counter({‘a’: 140, ‘c’: 100, ‘b’: 88})

Time complexity: O(n*m), where n is the length of the list and m is the average number of keys in each dictionary.
Auxiliary space: O(k), where k is the number of unique keys in all dictionaries combined. 

Method #3: Naive Method 




# Python code to demonstrate
# return the sum of values of dictionary
# with same keys in list of dictionary
 
from operator import itemgetter
 
# Initialising list of dictionary
ini_dict = [{'a':5, 'b':10, 'c':90},
            {'a':45, 'b':78},
            {'a':90, 'c':10}]
 
# printing initial dictionary
print ("initial dictionary", str(ini_dict))
 
# sum the values with same keys
result = {}
for d in ini_dict:
    for k in d.keys():
        result[k] = result.get(k, 0) + d[k]
 
 
print("resultant dictionary : ", str(result))

Output:

initial dictionary [{‘b’: 10, ‘c’: 90, ‘a’: 5}, {‘b’: 78, ‘a’: 45}, {‘c’: 10, ‘a’: 90}] resultant dictionary : {‘b’: 88, ‘c’: 100, ‘a’: 140}

Time complexity: O(n*m).
Auxiliary space: O(k).

Method 4: Using a dictionary comprehension

Another approach to sum the values of dictionaries with the same key in a list of dictionaries is to use dictionary comprehension. This method is concise and can be easier to read than the other methods, depending on your personal preferences. Here’s an example of how you can use dictionary comprehension to achieve the same result as the other methods:




ini_dict = [{'a':5, 'b':10, 'c':90},
            {'a':45, 'b':78},
            {'a':90, 'c':10}]
 
# Create a dictionary with keys and values obtained by iterating over the keys in the dictionaries
# and summing the values for each key.
result = {k: sum(d[k] for d in ini_dict if k in d) for k in set(k for d in ini_dict for k in d)}
 
print(result)  # Output: {'b': 88, 'a': 140, 'c': 100}
#This code is contributed by Edula Vinay Kumar Reddy

Output
{'a': 140, 'c': 100, 'b': 88}

Time complexity: O(n * m), where n is the number of dictionaries in the list and m is the average number of keys in each dictionary. This is because dictionary comprehension iterates over all the keys in all the dictionaries and sums the values for each key.
Auxiliary space: O(n * m), because the resulting dictionary will have at most n * m key-value pairs.

Method #5 Using defaultdict

This method uses defaultdict to create a dictionary where the default value for any key is set to 0. This allows us to easily add up the values for each key as we iterate over the list of dictionaries.




from collections import defaultdict
 
# Initialising list of dictionary
ini_dict = [{'a':5, 'b':10, 'c':90},
            {'a':45, 'b':78},
            {'a':90, 'c':10}]
 
# sum the values with same keys
result = defaultdict(int)
for d in ini_dict:
    for k, v in d.items():
        result[k] += v
 
print("resultant dictionary : ", dict(result))

Output
resultant dictionary :  {'a': 140, 'b': 88, 'c': 100}

Time Complexity: O(n*k), where n is the number of dictionaries in the list and k is the maximum number of keys in any dictionary. This is because we iterate over each dictionary in the list, and for each dictionary, we iterate over its keys and add its values to the corresponding key in the result dictionary.
Auxiliary Space: O(k), where k is the maximum number of keys in any dictionary. This is because we create a result dictionary with a default value of 0 for each key in the dictionary

Method 6: Using defaultdict from the collections module.

Approach:

  1. Import the defaultdict module from collections.
  2. Initialize a defaultdict object with the int() function as the default_factory argument. This means that when a new key is encountered, the defaultdict will automatically create a new entry with a value of 0.
  3. Loop through each dictionary in the list of dictionaries.
  4. Loop through each key-value pair in the dictionary.
  5. Use the key to access the corresponding value in the defaultdict and add the value from the current dictionary to it.
  6. Return the resulting dictionary.




from collections import defaultdict
 
# Initialising list of dictionary
ini_dict = [{'a':5, 'b':10, 'c':90},
            {'a':45, 'b':78},
            {'a':90, 'c':10}]
 
# printing initial dictionary
print("initial dictionary", str(ini_dict))
 
# sum the values with same keys using defaultdict
result = defaultdict(int)
for d in ini_dict:
    for k, v in d.items():
        result[k] += v
 
print("resultant dictionary : ", dict(result))

Output
initial dictionary [{'a': 5, 'b': 10, 'c': 90}, {'a': 45, 'b': 78}, {'a': 90, 'c': 10}]
resultant dictionary :  {'a': 140, 'b': 88, 'c': 100}

Time complexity: O(n*m) where n is the number of dictionaries in the list and m is the average number of key-value pairs in each dictionary.
Auxiliary space: O(m) where m is the number of unique keys across all dictionaries in the list.


Article Tags :