Python - Nested record values summation
Last Updated :
17 May, 2023
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 performed.
Method #1: Using loop
This is a brute force way in which we can perform this task. In this, we iterate through the nested dictionary summing up the values and assigning to respective key.
Python3
# Python3 code to demonstrate working of
# Nested record values summation
# Using loop
# initializing dictionary
test_dict = {'gfg' : {'a' : 4, 'b' : 5, 'c' : 6},
'is' : {'a': 2, 'b' : 9, 'c' : 10},
'best' : {'a' : 10, 'b' : 2, 'c' : 12}}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# Nested record values summation
# Using loop
res = dict()
for sub in test_dict:
sum = 0
for keys in test_dict[sub]:
sum = sum + test_dict[sub][keys]
res[sub] = sum
# printing result
print("The dictionary after keys summation is : " + str(res))
Output : The original dictionary is : {'best': {'a': 10, 'c': 12, 'b': 2}, 'is': {'a': 2, 'c': 10, 'b': 9}, 'gfg': {'a': 4, 'c': 6, 'b': 5}}
The dictionary after keys summation is : {'best': 24, 'is': 21, 'gfg': 15}
Time Complexity: O(n*n), where n is the values in dictionary
Auxiliary Space: O(n), where n is the size of dictionary
Method #2 : Using sum() This is yet another way in which this task can be performed. In this, we perform the task of computation using sum().
Python3
# Python3 code to demonstrate working of
# Nested record values summation
# Using sum()
from collections import Counter
# initializing dictionary
test_dict = {'gfg' : {'a' : 4, 'b' : 5, 'c' : 6},
'is' : {'a': 2, 'b' : 9, 'c' : 10},
'best' : {'a' : 10, 'b' : 2, 'c' : 12}}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# Nested record values summation
# Using sum()
res = dict()
for sub in test_dict:
res[sub] = sum([test_dict[sub][ele] for ele in test_dict[sub]])
# printing result
print("The dictionary after keys summation is : " + str(dict(res)))
Output : The original dictionary is : {'best': {'a': 10, 'c': 12, 'b': 2}, 'is': {'a': 2, 'c': 10, 'b': 9}, 'gfg': {'a': 4, 'c': 6, 'b': 5}}
The dictionary after keys summation is : {'best': 24, 'is': 21, 'gfg': 15}
Time complexity: O(NM), where N is the number of keys in the dictionary test_dict, and M is the number of subkeys in each nested record.
Auxiliary space: O(N), where N is the number of keys in the dictionary test_dict.
Method #3 : Using dictionary+ values()
Define an empty dictionary result to store the final summation of keys.Loop over the keys of the main dictionary.
Define a variable temp_sum to store the summation of values of each key in the nested dictionary.Loop over the values of the nested dictionary of the current key and add the values.Add the temp_sum value to the result dictionary with the current key as the key for the result. Return the result dictionary as the final output.
Python3
# original dictionary
orig_dict = {'best': {'a': 10, 'c': 12, 'b': 2}, 'is': {'a': 2, 'c': 10, 'b': 9}, 'gfg': {'a': 4, 'c': 6, 'b': 5}}
# empty dictionary to store the final summation
result = {}
# loop over keys of original dictionary
for key in orig_dict:
# initialize temporary sum variable
temp_sum = 0
# loop over values of nested dictionary and add to temp_sum
for val in orig_dict[key].values():
temp_sum += val
# add temp_sum value to result dictionary with current key as key for result
result[key] = temp_sum
# print final result
print("The dictionary after keys summation is :", result)
OutputThe dictionary after keys summation is : {'best': 24, 'is': 21, 'gfg': 15}
Time complexity: O(n*m)
Auxiliary Space: O(n)
Method #4 : Using dictionary+sum()
In this method, we still begin with the original dictionary. However, instead of using a for loop to iterate over each key and calculate the sum of the nested values, we use dictionary comprehension to create a new dictionary that has the same keys as the original dictionary but with the values replaced by the sum of the nested values. The expression {key: sum(original_dict[key].values()) for key in original_dict} creates a new dictionary by iterating over each key in the original dictionary, accessing the nested dictionary associated with that key using original_dict[key], and then using the sum() function to calculate the sum of the values in the nested dictionary. The result is a new dictionary with the same keys as the original dictionary, but with the values replaced by the sum of the nested values. we print the new dictionary to verify that the summation was done correctly.
Python3
# original dictionary
original_dict = {'best': {'a': 10, 'c': 12, 'b': 2},
'is': {'a': 2, 'c': 10, 'b': 9},
'gfg': {'a': 4, 'c': 6, 'b': 5}}
# use dictionary comprehension to create a new dictionary with summed values for each key
result_dict = {key: sum(original_dict[key].values()) for key in original_dict}
# print the result dictionary
print("The dictionary after keys summation is :", result_dict)
OutputThe dictionary after keys summation is : {'best': 24, 'is': 21, 'gfg': 15}
Time complexity: O(n*m)
Auxiliary Space: O(n*m)
Method #5 : Using dictionary comprehension and reduce():
Steps:
- Initialize an empty dictionary called res to store the result.
- For each key-value pair in the original dictionary:
a. Access the dictionary values using the key and iterate over them.
b. Sum the values using the built-in sum() function and store it in the res dictionary with the same key. - Print the res dictionary.
Python3
from functools import reduce
# initializing dictionary
test_dict = {'gfg': {'a': 4, 'b': 5, 'c': 6},
'is': {'a': 2, 'b': 9, 'c': 10},
'best': {'a': 10, 'b': 2, 'c': 12}}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# Nested record values summation
# Using reduce()
res = {key: reduce(lambda x, y: x + y, values.values())
for key, values in test_dict.items()}
# printing result
print("The dictionary after keys summation is : " + str(res))
# This code is contributed by Jyothi pinjala
OutputThe original dictionary is : {'gfg': {'a': 4, 'b': 5, 'c': 6}, 'is': {'a': 2, 'b': 9, 'c': 10}, 'best': {'a': 10, 'b': 2, 'c': 12}}
The dictionary after keys summation is : {'gfg': 15, 'is': 21, 'best': 24}
Time complexity: O(N^2) where n is the number of keys in the dictionary. This is because the algorithm requires iterating over all the keys in the dictionary, and then iterating over all the values for each key to calculate the sum.
Auxiliary space: O(N), as the output dictionary will contain the same number of keys as the input dictionary, and there are no additional data structures or variables used in the algorithm.
Method 6: Using the map() function + lambda function
- The program initializes the original dictionary called orig_dict, which contains nested dictionaries with keys 'best', 'is', and 'gfg'.
- The nested dictionaries contain three keys: 'a', 'b', and 'c', which each has an associated value.
- The program then uses the map() function to apply a lambda function to each item in the orig_dict dictionary.
- The lambda function takes each key-value pair in orig_dict, and returns a tuple where the first element is the key, and the second element is the sum of the values in the nested dictionary.
- The map() function returns an iterable of tuples that contain the new key-value pairs.
- The program then uses the dict() function to convert the iterable of tuples to a dictionary, which is assigned to the variable result.
- Finally, the program prints the result dictionary to the console.
Python3
# Initializing dictionary
orig_dict = {'best': {'a': 10, 'c': 12, 'b': 2}, 'is': {
'a': 2, 'c': 10, 'b': 9}, 'gfg': {'a': 4, 'c': 6, 'b': 5}}
result = dict(map(lambda x: (x[0], sum(x[1].values())), orig_dict.items()))
# Printing answer
print("The dictionary after keys summation is:", result)
OutputThe dictionary after keys summation is: {'best': 24, 'is': 21, 'gfg': 15}
Time complexity: O(n), where n is the number of keys in the original dictionary.
Auxiliary Space: O(n) as well since we are creating a new dictionary to store the final summation.
Similar Reads
Python - Skew Nested Tuple Summation
Given a Tuple, nesting at 2nd position, return summation of 1st elements. Input : test_tup = (5, (6, (1, (9, None)))) Output : 21 Explanation : 9 + 6 + 5 + 1 = 21. Input : test_tup = (5, (6, (1, None))) Output : 12 Explanation : 1 + 6 + 5 = 12. Method #1: Using infinite loop In this, we perform get
6 min read
Python - Nested Dictionary values summation
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
8 min read
Python - Index Value Summation List
To access the elements of lists, there are various methods. But sometimes we may require to access the element along with the index on which it is found and compute its summation, and for that, we may need to employ different strategies. This article discusses some of those strategies. Method 1: Nai
4 min read
Python | Selective Records Value Summation
Sometimes, while using a list of tuples, we come across a problem in which we have e certain list of keys and we just need the summation of values of those keys from the list of tuples. This has a utility in rating or summation of specific entities. Letâs discuss certain ways in which this can be do
11 min read
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 tuples in list
Sometimes, while working with records, we can have a problem in which we need to find the cumulative sum of all the values that are present in tuples. This can have applications in cases in which we deal with a lot of record data. Let's discuss certain ways in which this problem can be solved. Metho
7 min read
Python | Chuncked summation every K value
The prefix array is quite famous in the programming world. This article would discuss a variation of this scheme. To perform a chunked summation where the sum resets at every occurrence of the value K , we need to modify the summation logic. The idea is:Traverse the list.Keep adding to the cumulativ
3 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 - Remove nested records from tuple
Sometimes, while working with records, we can have a problem in which an element of a record is another tuple records and we might have to remove the nested records. This is a problem which does not occur commonly, but having a solution to it is useful. Letâs discuss certain way in which this task c
5 min read
Python - Sort Dictionary by key-value Summation
Given a Dictionary, sort by summation of key and value. Input : test_dict = {3:5, 1:3, 4:6, 2:7, 8:1} Output : {1: 3, 3: 5, 2: 7, 8: 1, 4: 6} Explanation : 4 < 8 < 9 = 9 < 10 are increasing summation of keys and values. Input : test_dict = {3:5, 1:3, 4:6, 2:7} Output : {1: 3, 3: 5, 2: 7, 4:
5 min read