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 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))
|
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 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)))
|
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.
# 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)
|
The 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.
# 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)
|
The 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.
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 |
The 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.
# 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)
|
The 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.