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
import collections, functools, operator
ini_dict = [{ 'a' : 5 , 'b' : 10 , 'c' : 90 },
{ 'a' : 45 , 'b' : 78 },
{ 'a' : 90 , 'c' : 10 }]
print ("initial dictionary", str (ini_dict))
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
import collections
ini_dict = [{ 'a' : 5 , 'b' : 10 , 'c' : 90 },
{ 'a' : 45 , 'b' : 78 },
{ 'a' : 90 , 'c' : 10 }]
print ("initial dictionary", str (ini_dict))
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
from operator import itemgetter
ini_dict = [{ 'a' : 5 , 'b' : 10 , 'c' : 90 },
{ 'a' : 45 , 'b' : 78 },
{ 'a' : 90 , 'c' : 10 }]
print ("initial dictionary", str (ini_dict))
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 }]
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
{'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
ini_dict = [{ 'a' : 5 , 'b' : 10 , 'c' : 90 },
{ 'a' : 45 , 'b' : 78 },
{ 'a' : 90 , 'c' : 10 }]
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:
- 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
ini_dict = [{ 'a' : 5 , 'b' : 10 , 'c' : 90 },
{ 'a' : 45 , 'b' : 78 },
{ 'a' : 90 , 'c' : 10 }]
print ( "initial dictionary" , str (ini_dict))
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.
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 - 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 - Keys with shortest length lists in dictionary
Sometimes, while working with Python lists, we can have problem in which we need to return the keys which have minimum lengths of lists as values. This can have application in domains in which we work with data. Lets discuss certain ways in which this task can be performed. Method #1: Using len() +
4 min read
Filter List of Python Dictionaries by Key in Python
In Python, filtering a list of dictionaries based on a specific key is a common task when working with structured data. In this article, weâll explore different ways to filter a list of dictionaries by key from the most efficient to the least. Using List Comprehension List comprehension is a concise
3 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 defau
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,
2 min read
Get all Unique Keys from a List of Dictionaries - Python
Our task is to get all unique keys from a list of dictionaries and we are given a list where each element is a dictionary, we need to extract and return a list of keys that appear across all dictionaries. The result should contain each key only once regardless of how many times it appears. For examp
3 min read
Python - Add Values to Dictionary of List
A dictionary of lists allows storing grouped values under specific keys. For example, in a = {'x': [10, 20]}, the key 'x' maps to the list [10, 20]. To add values like 30 to this list, we use efficient methods to update the dictionary dynamically. Letâs look at some commonly used methods to efficien
3 min read
Python - List of dictionaries all values Summation
Given a list of dictionaries, extract all the values summation. Input : test_list = [{"Apple" : 2, "Mango" : 2, "Grapes" : 2}, {"Apple" : 2, "Mango" : 2, "Grapes" : 2}] Output : 12 Explanation : 2 + 2 +...(6-times) = 12, sum of all values. Input : test_list = [{"Apple" : 3, "Mango" : 2, "Grapes" : 2
5 min read