Open In App

Python – Summation of Custom nested keys in Dictionary

Last Updated : 09 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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))


Output

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


Output

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


Output

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


Output

The 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:

  1. Import the reduce() function from the functools module.
  2. Define the dictionary test_dict containing nested keys and values.
  3. Initialize a list sum_key containing keys to sum over.
  4. Use the reduce() function with a lambda expression to sum over the selected keys in the dictionary.
  5. 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))


Output

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


Output

The 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

  1. Initialize an empty stack and push the root dictionary onto it, along with a running total of 0.
  2. While the stack is not empty, perform the following steps:
    1. pop the top dictionary off the stack.
    2. 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.
    3. If an item’s value is itself a dictionary, push it onto the stack.
  3. 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)


Output

The 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 - 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 can be performed. Method #1 : Using loop + items(
8 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" : 10}, K = 19 Output : ['Best', 'Geeks'] Explana
9 min read
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's discuss certain ways in which this task can be p
7 min read
Python - Extract selective keys' values Including Nested Keys
Sometimes, while working with Python dictionaries, we can have a problem in which we need to extract selective keys' values. This problem has been solved earlier, but sometimes, we can have multiple nestings and certain keys may be present in inner records. This problem caters all the nestings for extraction of keys' values. Let's discuss certain w
7 min read
Python | Add keys to nested dictionary
Addition of keys in dictionaries have been discussed many times, but sometimes, we might have a problem in which we require to alter/add keys in the nested dictionary. This type of problem is common in today's world with advent of NoSQL databases. Let's discuss certain ways in which this problem can be solved. Method #1: Using for loop Step-by-step
5 min read
Python | Safe access nested dictionary keys
Sometimes, while working with Python we can have a problem in which we need to get the 2nd degree key of dictionary i.e the nested key. This type of problem is common in case of web development, especially with the advent of NoSQL databases. Let's discuss certain ways to safely get the nested available key in dictionary. Method #1 : Using nested ge
3 min read
Python - Sorted Nested Keys in Dictionary
Sometimes, while working with Python dictionaries, we can have a problem in which we need to extract all the keys of nested dictionaries and render them in sorted order. This kind of application can occur in domains in which we work with data. Lets discuss certain ways in which this task can be performed. Method #1 : Using yield + isinstance() + lo
4 min read
Python - Convert Nested Tuple to Custom Key Dictionary
Sometimes, while working with Python records, we can have data that come without proper column names/identifiers, which can just be identified by their index, but we intend to assign them keys and render in form of dictionaries. This kind of problem can have applications in domains such as web development. Let's discuss certain ways in which this t
4 min read
Python - Test if custom keys equal to K in dictionary
Given dictionary and custom keys list, check if all those custom keys equals K. Input : test_dict = {"Gfg" : 5, "is" : 8, "Best" : 10, "for" : 10, "Geeks" : 10}, cust_keys = ["is", "for", "Geeks"], K = 10 Output : False Explanation : "is" is having 8 as value not 10, hence False Input : test_dict = {"Gfg" : 5, "is" : 10, "Best" : 10, "for" : 10, "G
6 min read
Different ways of sorting Dictionary by Keys and Reverse sorting by keys
Prerequisite: Dictionaries in Python A dictionary is a collection which is unordered, changeable and indexed. In Python, dictionaries are written with curly brackets, and they have keys and values. We can access the values of the dictionary using keys. In this article, we will discuss 10 different ways of sorting the Python dictionary by keys and a
8 min read
Practice Tags :