Python - Summation of Custom nested keys in Dictionary
Last Updated :
09 Apr, 2023
Given a dictionary with keys as nested dictionaries, find the sum of values of certain custom keys inside the nested dictionary.
Input : test_dict = {'Gfg' : {1 : 6, 5: 9, 9: 12}, 'is' : {1 : 9, 5: 7, 9: 2}, 'best' : {1 : 3, 5: 4, 9: 14}}, sum_key = [1]
Output : 18
Explanation : 6 + 9 + 3 = 18, only values with key 1 are summed.
Input : test_dict = {'Gfg' : {1 : 6, 5: 9, 9: 12}, 'is' : {1 : 9, 5: 7, 9: 2}, 'best' : {1 : 3, 5: 4, 9: 14}}, sum_key = [5, 9]
Output : 48
Explanation : Keys 5, 9 are summed.
Method #1: loop
This is the brute way in which this problem can be solved. In this, we employ a loop for all the list elements and keep updating sum value from all the nested dictionaries.
Python3
# Python3 code to demonstrate working of
# Summation of Custom nested keys in Dictionary
# Using loop
# initializing dictionary
test_dict = {'Gfg' : {1 : 6, 5: 9, 9: 12},
'is' : {1 : 9, 5: 7, 9: 2},
'best' : {1 : 3, 5: 4, 9: 14}}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing sum keys
sum_key = [1, 9]
sum = 0
for ele in sum_key:
for key, val in test_dict.items():
# extracting summation of required values
sum = sum + val[ele]
# printing result
print("The required summation : " + str(sum))
OutputThe original dictionary is : {'Gfg': {1: 6, 5: 9, 9: 12}, 'is': {1: 9, 5: 7, 9: 2}, 'best': {1: 3, 5: 4, 9: 14}}
The required summation : 46
Time complexity: O(n*m), where n is the number of keys in the dictionary and m is the number of sum keys.
Auxiliary space: O(1), as only a constant amount of extra space is used to store the sum and loop variables.
Method #2 : Using list comprehension + sum()
The combination of above functions can also be employed to solve this problem. In this, we perform the task of summation using sum() and rest logic is also encapsulated as one-liner using list comprehension.
Python3
# Python3 code to demonstrate working of
# Summation of Custom nested keys in Dictionary
# Using list comprehension + sum()
# initializing dictionary
test_dict = {'Gfg' : {1 : 6, 5: 9, 9: 12},
'is' : {1 : 9, 5: 7, 9: 2},
'best' : {1 : 3, 5: 4, 9: 14}}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing sum keys
sum_key = [1, 9]
# sum() used to get cumulative summation
res = sum([val[ele] for ele in sum_key for key, val in test_dict.items()])
# printing result
print("The required summation : " + str(res))
OutputThe original dictionary is : {'Gfg': {1: 6, 5: 9, 9: 12}, 'is': {1: 9, 5: 7, 9: 2}, 'best': {1: 3, 5: 4, 9: 14}}
The required summation : 46
The time complexity of this code is O(NM), where N is the number of inner dictionaries in test_dict and M is the length of sum_key.
The auxiliary space of this code is O(1) because no additional data structures are being created.
METHOD 3: use the built-in function reduce() from the functools module
we define a lambda function sum_func that takes an accumulator (acc) and a key (key) and returns the sum of the values associated with that key in each dictionary in test_dict. We use the get() method to safely access the value of the key, returning 0 if the key is not present.
Python3
from functools import reduce
test_dict = {'Gfg' : {1 : 6, 5: 9, 9: 12},
'is' : {1 : 9, 5: 7, 9: 2},
'best' : {1 : 3, 5: 4, 9: 14}}
sum_key = [1, 9]
# Define a lambda function to sum the values of the nested keys
sum_func = lambda acc, key: acc + sum(val.get(key, 0) for val in test_dict.values())
# Use reduce() to apply the lambda function to each key in sum_key and accumulate the results
res = reduce(sum_func, sum_key, 0)
print("The required summation : " + str(res))
OutputThe required summation : 46
The time complexity of this approach is O(N*K), where N is the number of dictionaries in test_dict and K is the number of keys in sum_key.
The auxiliary space complexity of this approach is O(1) because we are only using constant additional space for the accumulator and the lambda function.
Method #4: use the map comprehension
- The map() function is used to apply a lambda function to each element in sum_key.
- The lambda function first loops over each dictionary in test_dict extracts the value corresponding to the key from the inner dictionary using the key k, and then returns the sum of all these values.
- The sum() function is used to find the sum of all the values extracted using the map() function. This sum is stored in the variable res.
Python3
# Python3 code to demonstrate working of
# Summation of Custom nested keys in Dictionary
# Using map() + sum()
# initializing dictionary
test_dict = {'Gfg' : {1 : 6, 5: 9, 9: 12},
'is' : {1 : 9, 5: 7, 9: 2},
'best' : {1 : 3, 5: 4, 9: 14}}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing sum keys
sum_key = [1, 9]
# using map() to extract values
res = sum(map(lambda k: sum(test_dict[d][k] for d in test_dict), sum_key))
# printing result
print("The required summation : " + str(res))
OutputThe original dictionary is : {'Gfg': {1: 6, 5: 9, 9: 12}, 'is': {1: 9, 5: 7, 9: 2}, 'best': {1: 3, 5: 4, 9: 14}}
The required summation : 46
Time complexity: O(N*K) where N is the number of dictionaries in test_dict and K is the number of keys in sum_key.
Space Complexity: O(1) because we are only using constant additional space.
Method #4: Using reduce() and lambda function
Step by step Algorithm:
- Import the reduce() function from the functools module.
- Define the dictionary test_dict containing nested keys and values.
- Initialize a list sum_key containing keys to sum over.
- Use the reduce() function with a lambda expression to sum over the selected keys in the dictionary.
- Print the result.
Python3
from functools import reduce
# initializing dictionary
test_dict = {'Gfg' : {1 : 6, 5: 9, 9: 12},
'is' : {1 : 9, 5: 7, 9: 2},
'best' : {1 : 3, 5: 4, 9: 14}}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing sum keys
sum_key = [1, 9]
# using reduce() and lambda expression to get the required summation
sum = reduce(lambda x, y: x + y,
[test_dict[val][ele] for ele in sum_key for val in test_dict])
# printing result
print("The required summation : " + str(sum))
OutputThe original dictionary is : {'Gfg': {1: 6, 5: 9, 9: 12}, 'is': {1: 9, 5: 7, 9: 2}, 'best': {1: 3, 5: 4, 9: 14}}
The required summation : 46
Time Complexity: O(N*K) where N is the number of dictionaries in test_dict and K is the number of keys in sum_key.
Auxiliary Space: O(1) because we are only using constant additional space.
Method 5: Use a recursive function that traverses the nested dictionary.
Step-by-step approach:
- initialize a list called sum_key with the keys whose values we want to sum.
- Define a recursive function called sum_nested_keys() that takes a dictionary as input and returns the sum of the values of the required keys.
- Inside the sum_nested_keys() function, initialize a variable called sum_val to 0.
- Loop over the items of the dictionary using the items() method, which returns a view object of the dictionary's (key, value) pairs.
- For each item, check if its value is a dictionary using the isinstance() function.
- If it is, we recursively call the sum_nested_keys() function with the value as input and add the returned sum to sum_val.
- If the value is not a dictionary, check if its key is in the list of required keys sum_key. If it is, we add the value to sum_val.
- After looping over all items, return the final value of sum_val.
Below is the implementation of the above approach:
Python3
# Python3 code to demonstrate working of
# Summation of Custom nested keys in Dictionary
# Using recursive function
# initializing dictionary
test_dict = {'Gfg' : {1 : 6, 5: 9, 9: 12},
'is' : {1 : 9, 5: 7, 9: 2},
'best' : {1 : 3, 5: 4, 9: 14}}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing sum keys
sum_key = [1, 9]
# defining recursive function to sum the values of the required keys
def sum_nested_keys(dct):
sum_val = 0
for k, v in dct.items():
if isinstance(v, dict):
sum_val += sum_nested_keys(v)
elif k in sum_key:
sum_val += v
return sum_val
# calling the recursive function on the dictionary
res = sum_nested_keys(test_dict)
# printing result
print("The required summation : " + str(res))
OutputThe original dictionary is : {'Gfg': {1: 6, 5: 9, 9: 12}, 'is': {1: 9, 5: 7, 9: 2}, 'best': {1: 3, 5: 4, 9: 14}}
The required summation : 46
Time Complexity: O(n) where n is the number of elements in the dictionary, since we need to traverse all elements of the dictionary once.
Auxiliary Space: O(m) where m is the maximum depth of the nested dictionary, as we are storing the call stack of the recursive function up to the maximum depth.
Method #6: Using a stack-based iterative approach
- Initialize an empty stack and push the root dictionary onto it, along with a running total of 0.
- While the stack is not empty, perform the following steps:
- pop the top dictionary off the stack.
- Iterate through the dictionary's items. If an item's key is in the list of sum keys, add its value to the running total.
- If an item's value is itself a dictionary, push it onto the stack.
- Print the running total.
Implementation:
Python3
# Python program for the above approach
# Function to find the sum of nested keys
# with given values
def sum_nested_keys(dct):
stack = [(dct, 0)]
total = 0
# While Stack is non-empty
while stack:
# Find the current top
cur_dict, cur_total = stack.pop()
for k, v in cur_dict.items():
if k in sum_key:
cur_total += v
elif isinstance(v, dict):
stack.append((v, cur_total))
# Update the total sum
total += cur_total
print("The required summation : " + str(total))
# Return the resultant sum
return total
# Driver Code
test_dict = {'Gfg' : {1 : 6, 5: 9, 9: 12},
'is' : {1 : 9, 5: 7, 9: 2},
'best' : {1 : 3, 5: 4, 9: 14}}
sum_key = [1, 9]
print("The original dictionary is : " + str(test_dict))
res = sum_nested_keys(test_dict)
OutputThe original dictionary is : {'Gfg': {1: 6, 5: 9, 9: 12}, 'is': {1: 9, 5: 7, 9: 2}, 'best': {1: 3, 5: 4, 9: 14}}
The required summation : 46
Time Complexity: O(N), where N is the number of items in the nested dictionary.
Auxiliary Space: O(N), for the stack.
Similar Reads
Python - Custom Tuple Key Summation in Dictionary
Sometimes, while working with Python dictionaries, we can have a problem in which we need to perform group summation of values, of certain key on particular index of tuple keys of dictionary. This problem is quite custom, but can have application in domains that revolves around data processing. Let'
7 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
Count the Key from Nested Dictionary in Python
In Python, counting the occurrences of keys within a nested dictionary often requires traversing through its complex structure. In this article, we will see how to count the key from the nested dictionary in Python. Count the Key from the Nested Dictionary in PythonBelow are some ways and examples b
4 min read
Convert Nested Dictionary to List in Python
In this article, weâll explore several methods to Convert Nested Dictionaries to a List in Python. List comprehension is the fastest and most concise way to convert a nested dictionary into a list.Pythona = { "a": {"x": 1, "y": 2}, "b": {"x": 3, "y": 4}, } # Convert nested dictionary to a list of li
3 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
Convert Nested Tuple to Custom Key Dictionary - Python
The task is to convert a nested tuple into a dictionary with custom keys. Each tuple in the nested structure contains multiple elements, and the goal is to map these elements to specific keys in a dictionary.For example, given the tuple a = ((4, 'Gfg', 10), (3, 'is', 8), (6, 'Best', 10)), the goal i
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 - 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 | 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
Create Nested Dictionary using given List - Python
The task of creating a nested dictionary in Python involves pairing the elements of a list with the key-value pairs from a dictionary. Each key from the list will map to a dictionary containing a corresponding key-value pair from the original dictionary. For example, given the dictionary a = {'Gfg':
3 min read