Python – Nested Dictionary values summation
Last Updated :
05 Apr, 2023
Sometimes, while working with Python dictionaries, we can have problem in which we have nested records and we need cumulative summation of it’s keys values. This can have possible application in domains such as web development and competitive programming. Lets discuss certain ways in which this task can be performed.
Method #1 : Using loop + items() + values() The combination of above functionalities can be used to solve this problem. In this, we iterate through all the values extracted using values() and perform the task of summation.
Step-by-step approach:
- An empty dictionary res is initialized.
- A loop is initiated over the values of test_dict using test_dict.values().
- Within the outer loop, an inner loop is initiated over the items of the sub-dictionary using sub.items().
- Inside the inner loop, the current element value is added to the corresponding key in the res dictionary using the res.get() method, which returns the value for the given key if it exists, or 0 if it does not.
- The updated res dictionary is printed using the print() function.
- The program execution is complete
Below is the implementation of the above approach:
Python3
test_dict = { 'gfg' : { 'a' : 4 , 'b' : 5 , 'c' : 8 },
'is' : { 'a' : 8 , 'c' : 10 },
'best' : { 'c' : 19 , 'b' : 10 }}
print ("The original dictionary is : " + str (test_dict))
res = dict ()
for sub in test_dict.values():
for key, ele in sub.items():
res[key] = ele + res.get(key, 0 )
print ("The summation dictionary is : " + str (res))
|
Output :
The original dictionary is : {‘gfg’: {‘a’: 4, ‘b’: 5, ‘c’: 8}, ‘best’: {‘b’: 10, ‘c’: 19}, ‘is’: {‘a’: 8, ‘c’: 10}} The summation dictionary is : {‘a’: 12, ‘b’: 15, ‘c’: 37}
Time complexity: O(n*m).
Auxiliary space: O(m).
Method #2 : Using Counter() + values() The combination of above methods can be used to perform this task. In this, we save the required frequency using Counter() and extraction of values can be done using values(). Method #2 : Using Counter() + values() Th
Python3
from collections import Counter
test_dict = { 'gfg' : { 'a' : 4 , 'b' : 5 , 'c' : 8 },
'is' : { 'a' : 8 , 'c' : 10 },
'best' : { 'c' : 19 , 'b' : 10 }}
print ("The original dictionary is : " + str (test_dict))
res = Counter()
for val in test_dict.values():
res.update(val)
print ("The summation dictionary is : " + str ( dict (res)))
|
Output :
The original dictionary is : {‘gfg’: {‘a’: 4, ‘b’: 5, ‘c’: 8}, ‘best’: {‘b’: 10, ‘c’: 19}, ‘is’: {‘a’: 8, ‘c’: 10}} The summation dictionary is : {‘a’: 12, ‘b’: 15, ‘c’: 37}
Time complexity: O(NM), where N is the number of keys in the outer dictionary and M is the number of keys in the inner dictionaries. This is because we are iterating over each inner dictionary for each outer dictionary key.
Auxiliary space: O(NM), as we are creating a Counter object to store the summation of values from the inner dictionaries. This object will have an entry for each unique key in the inner dictionaries, which can be at most N*M.
Method #3 : Using dictionary comprehension and sum():
Algorithm:
1.Initialize the dictionary ‘test_dict’.
2.Using dictionary comprehension and sum(), find the summation of all values for each unique key present in all the nested dictionaries.
3.Store the result in the dictionary ‘res’.
4.Print the original dictionary ‘test_dict’ and the summation dictionary ‘res’.
Python3
test_dict = { 'gfg' : { 'a' : 4 , 'b' : 5 , 'c' : 8 },
'is' : { 'a' : 8 , 'c' : 10 },
'best' : { 'c' : 19 , 'b' : 10 }}
print ( "The original dictionary is : " + str (test_dict))
res = {key: sum (d.get(key, 0 ) for d in test_dict.values()) for key in set ().union( * test_dict.values())}
print ( "The summation dictionary is : " + str (res))
|
Output
The original dictionary is : {'gfg': {'a': 4, 'b': 5, 'c': 8}, 'is': {'a': 8, 'c': 10}, 'best': {'c': 19, 'b': 10}}
The summation dictionary is : {'b': 15, 'a': 12, 'c': 37}
Time Complexity: O(n).
In the worst case, the algorithm iterates through all the keys and values of the nested dictionaries twice, which gives us a time complexity of O(n*m), where n is the number of outer keys and m is the number of inner keys. But since we are using dictionary comprehension and sum(), the time complexity can be considered as O(n).
Auxiliary Space: O(k)
The algorithm uses two dictionaries, ‘test_dict’ and ‘res’, which store the original dictionary and the result respectively. The space used is proportional to the number of unique keys present in all the nested dictionaries. Hence the space complexity can be considered as O(k), where k is the number of unique keys present in all the nested dictionaries.
Method #4: Using defaultdict
Use the defaultdict from the collections module to simplify the code for nested dictionary values summation
Step-by-step approach:
- Import the defaultdict from the collections module.
- Initialize the dictionary test_dict with nested dictionaries.
- Print the original dictionary.
- Create a defaultdict res with default value 0. This means that if a key is not present in the dictionary, it will have a value of 0.
- Iterate through the values of test_dict using a for loop. For each inner dictionary, iterate through its items using another for loop. For each key-value pair, add the value to the corresponding key in res.
- Convert the defaultdict res to a regular dictionary using the dict() constructor.
- Print the result.
Below is the implementation of the above approach:
Python3
from collections import defaultdict
test_dict = { 'gfg' : { 'a' : 4 , 'b' : 5 , 'c' : 8 },
'is' : { 'a' : 8 , 'c' : 10 },
'best' : { 'c' : 19 , 'b' : 10 }}
print ( "The original dictionary is : " + str (test_dict))
res = defaultdict( int )
for inner_dict in test_dict.values():
for key, value in inner_dict.items():
res[key] + = value
res = dict (res)
print ( "The summation dictionary is : " + str (res))
|
Output
The original dictionary is : {'gfg': {'a': 4, 'b': 5, 'c': 8}, 'is': {'a': 8, 'c': 10}, 'best': {'c': 19, 'b': 10}}
The summation dictionary is : {'a': 12, 'b': 15, 'c': 37}
Time complexity: O(nm), where n is the number of keys in the outer dictionary and m is the number of keys in the largest inner dictionary.
Auxiliary space: O(k), where k is the number of unique keys in the nested dictionaries.
Method #5: Using itertools.chain() and collections.defaultdict()
Use itertools.chain() to flatten the nested dictionary into a single iterable, and then use collections.defaultdict() to create a dictionary with default value as 0. Then iterate over the flattened iterable and add the values to the corresponding keys in the defaultdict.
Step-by-step approach:
- Import the itertools and collections modules.
- Define a nested dictionary named “test_dict” that contains several key-value pairs.
- Print the original dictionary.
- Create an empty defaultdict named “res” using the collections module. This dictionary will be used to store the sum of values for each key.
- Loop through the outer keys and values of “test_dict” using the items() method.
- For each outer key-value pair, loop through the inner keys and values using the items() method.
- For each inner key-value pair, add the value to the corresponding key in the “res” defaultdict.
- Print the resulting summation dictionary by converting the “res” defaultdict to a regular dictionary using the dict() function.
Below is the implementation of the above approach:
Python3
import itertools
import collections
test_dict = { 'gfg' : { 'a' : 4 , 'b' : 5 , 'c' : 8 },
'is' : { 'a' : 8 , 'c' : 10 },
'best' : { 'c' : 19 , 'b' : 10 }}
print ( "The original dictionary is : " + str (test_dict))
res = collections.defaultdict( int )
for key, sub_dict in test_dict.items():
for k, v in sub_dict.items():
res[k] + = v
print ( "The summation dictionary is : " + str ( dict (res)))
|
Output
The original dictionary is : {'gfg': {'a': 4, 'b': 5, 'c': 8}, 'is': {'a': 8, 'c': 10}, 'best': {'c': 19, 'b': 10}}
The summation dictionary is : {'a': 12, 'b': 15, 'c': 37}
Time complexity: O(n*m), where n is the number of keys in the outer dictionary and m is the maximum number of keys in the inner dictionaries.
Auxiliary space: O(n), to store the defaultdict.
Similar Reads
Python - Dictionary Values Mapped Summation
Given a dictionary with a values list, our task is to extract the sum of values, found using mappings. Input : test_dict = {4 : ['a', 'v', 'b', 'e'], 1 : ['g', 'f', 'g'], 3 : ['e', 'v']}, map_vals = {'a' : 3, 'g' : 8, 'f' : 10, 'b' : 4, 'e' : 7, 'v' : 2} Output : {4: 16, 1: 26, 3: 9} Explanation : "
6 min read
Python | Summation of dictionary list values
Sometimes, while working with Python dictionaries, we can have its values as lists. In this can, we can have a problem in that we just require the count of elements in those lists as a whole. This can be a problem in Data Science in which we need to get total records in observations. Let's discuss c
6 min read
Python | Value summation of key in dictionary
Many operations such as grouping and conversions are possible using Python dictionaries. But sometimes, we can also have a problem in which we need to perform the aggregation of values of key in dictionary list. This task is common in day-day programming. Let's discuss certain ways in which this tas
6 min read
Python - Product and Inter Summation dictionary values
Sometimes, while working with Python dictionaries, we can have a problem in which we need to perform product of entire value list and perform summation of product of each list with other. This kind of application in web development and day-day programming. Lets discuss certain ways in which this tas
4 min read
Python - Summation of tuple dictionary values
Sometimes, while working with data, we can have a problem in which we need to find the summation of tuple elements that are received as values of dictionary. We may have a problem to get index wise summation. Letâs discuss certain ways in which this particular problem can be solved. Method #1: Using
4 min read
Python - Dictionary values String Length Summation
Sometimes, while working with Python dictionaries we can have problem in which we need to perform the summation of all the string lengths which as present as dictionary values. This can have application in many domains such as web development and day-day programming. Lets discuss certain ways in whi
4 min read
Python - Sort Dictionary by Values Summation
Give a dictionary with value lists, sort the keys by summation of values in value list. Input : test_dict = {'Gfg' : [6, 7, 4], 'best' : [7, 6, 5]} Output : {'Gfg': 17, 'best': 18} Explanation : Sorted by sum, and replaced. Input : test_dict = {'Gfg' : [8], 'best' : [5]} Output : {'best': 5, 'Gfg':
4 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
Python - Dictionary Keys whose Values summation equals K
Given a dictionary and a value K, extract keys whose summation of values equals K. Input : {"Gfg" : 3, "is" : 5, "Best" : 9, "for" : 8, "Geeks" : 10}, K = 17 Output : ['Best', 'for'] Explanation : 9 + 8 = 17, hence those keys are extracted. Input : {"Gfg" : 3, "is" : 5, "Best" : 9, "for" : 8, "Geeks
9 min read
Python - Nested record values summation
Sometimes, while working with records, we can have problems in which we need to perform summation of nested keys of a key and record the sum as key's value. This can have possible applications in domains such as Data Science and web development. Let us discuss certain ways in which this task can be
7 min read