Python | Sum list of dictionaries with same key
Last Updated :
05 Apr, 2023
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:
- Import necessary modules - collections, functools, and operator.
- Initialize a list of dictionaries called "ini_dict" that contains dictionaries with some key-value pairs.
- Print the initial list of dictionaries.
- Use the map() function to create a list of Counter objects from the "ini_dict" list. The Counter object is a subclass of dictionary and is used to count the occurrences of elements in a collection.
- Use the reduce() function from functools module to combine the Counter objects in the list into a single dictionary. The reduce() function takes two arguments: a function and an iterable, and returns a single value obtained by applying the function to the elements of the iterable in a cumulative way.
- Use the dict() function to convert the resulting tuple into a dictionary.
- Print the resultant dictionary.
Below is the implementation of the above approach:
Python3
# 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:
- Import the collections module.
- Initialize a list of dictionaries called ini_dict.
- Print the initial dictionary using the print() function and passing the string representation of ini_dict.
- Initialize a Counter object called counter.
- Use a for loop to iterate over each dictionary in ini_dict.
- Use the update() method of the Counter object to add the values of the current dictionary to the counter.
- Convert the counter to a dictionary using the dict() function and store the result in a new dictionary called result.
- Print the resulting dictionary using the print() function and passing the string representation of result.
Below is the implementation of the above approach:
Python3
# 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
Python3
# 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:
Python3
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.
Python3
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))
Outputresultant 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:
- Import the defaultdict module from collections.
- 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.
- Loop through each dictionary in the list of dictionaries.
- Loop through each key-value pair in the dictionary.
- Use the key to access the corresponding value in the defaultdict and add the value from the current dictionary to it.
- Return the resulting dictionary.
Python3
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))
Outputinitial 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.
Similar Reads
Python Merge Dictionaries with Same Keys
When working with dictionaries in Python, you should understand that they are mutable, unordered collections of key-value pairs. This flexibility allows us to quickly merge dictionaries, but what happens when two dictionaries have the same key? Python allows us to manage this situation. In this arti
3 min read
Python - Dictionaries with Unique Value Lists
Given List of dictionaries with list values, extract unique dictionaries. Input : [{'Gfg': [2, 3], 'is' : [7, 8], 'best' : [10]}, {'Gfg': [2, 3], 'is' : [7, 8], 'best' : [10]}] Output : [{'Gfg': [2, 3], 'is': [7, 8], 'best': [10]}] Explanation : Both are similar dictionaries, and hence 1 is removed.
4 min read
Python | Segregating key's value in list of dictionaries
While working with dictionaries, we may encounter problems in which we need to segregate all the similar keys' values together. This kind of problem can occur in web development domain while working with databases. Let's discuss certain ways in which this problem can be solved. Method #1: Using gene
6 min read
Python - Add custom values key in List of dictionaries
The task of adding custom values as keys in a list of dictionaries involves inserting a new key-value pair into each dictionary within the list. In Python, dictionaries are mutable, meaning the key-value pairs can be modified or added easily. When working with a list of dictionaries, the goal is to
5 min read
Python | Sort dictionary keys to list
Sometimes, we wish to flatten the dictionary into list, the simple flattening is relatively easier, but when we wish to align keys and values in sorted way, i.e sorted by value, then it becomes quite a complex problem. Let's discuss certain ways in which this task can be performed. Method #1 : Using
4 min read
Python - Merge Dictionaries List with duplicate Keys
Given two List of dictionaries with possible duplicate keys, write a Python program to perform merge. Examples: Input : test_list1 = [{"gfg" : 1, "best" : 4}, {"geeks" : 10, "good" : 15}, {"love" : "gfg"}], test_list2 = [{"gfg" : 6}, {"better" : 3, "for" : 10, "geeks" : 1}, {"gfg" : 10}] Output : [{
4 min read
Inverse Dictionary Values List - Python
We are given a dictionary and the task is to create a new dictionary where each element of the value lists becomes a key and the original keys are grouped as lists of values for these new keys.For example: dict = {1: [2, 3], 2: [3], 3: [1]} then output will be {2: [1], 3: [1, 2], 1: [3]}Using defaul
2 min read
Get List of Values From Dictionary - Python
We are given a dictionary and our task is to extract all the values from it and store them in a list. For example, if the dictionary is d = {'a': 1, 'b': 2, 'c': 3}, then the output would be [1, 2, 3].Using dict.values()We can use dict.values() along with the list() function to get the list. Here, t
2 min read
Sorting Python Dictionary With Lists as Values
Python offers various methods to sort a dictionary with Lists as Values. This is a common task when dealing with data where you need to order elements based on different criteria. In this article, we will sort a dictionary with lists as values in Python. Sort a Dictionary with Lists as Values in Pyt
3 min read
Python | Initialize list with empty dictionaries
While working with Python, we can have a problem in which we need to initialize a list of a particular size with empty dictionaries. This task has it's utility in web development to store records. Let's discuss certain ways in which this task can be performed. Method #1 : Using {} + "*" operator Thi
5 min read