Finding the Summation of Nested Dictionary Values in Python


Sometimes we need to sum up the values of nested dictionary values so in this problem statement we are required to find the summation of the nested dictionary values using Python.

Understanding the Problem

The problem at hand is to find the summation of values present in the nested dictionary and we have to implement the code using Python. So the nested dictionaries are the dictionary inside the dictionary. And we have to find the nested values and sum them up as a result.

Sum for all the Nested Dictionary Values

In this approach we will add all the values present in the nested dictionary using the for loop.

Algorithm

  • Step 1 − Define the function called summation_values and inside this function we will pass the nested dictionary called the_dictionary as input.

  • Step 2 − Initialize the sum variable in which we will store the summation of all the values present in the nested dictionary.

  • Step 3 − A loop will be initiated for all the key-value pairs in the nested dictionary. And then the condition will be initiated to verify that the value is a number then add the value in the sum variable.

  • Step 4 − And If the integer number is in the nested dictionary so that call the above created function recursively and add the returned value to the sum.

  • Step 5 − End algorithm by returning the value of sum.

Example

# Function to get the summation of values
def summation_values(the_dictionary):
   sum = 0
   for value in the_dictionary.values():
      if isinstance(value, int):
         sum += value
      elif isinstance(value, dict):
         sum += summation_values(value)
   return sum
# input nested dictionary
nested_dict = {
   'apple': 10,
   'banana': {
      'cucumber': 12,
      'pineapple': {
         'orange': 23,
         'mango': 14
      }
   },
   'guava': 16
}

# pass the input dictionary and call the function
output = summation_values(nested_dict)

# show the output
print("The summation of nested dictionary values:", output)

Output

The summation of nested dictionary values: 75

Complexity

The time complexity of the summation_values function is O(N), here N is the number of key-value pairs in the dictionary. The reason for this complexity is that the function depends on the size of the input dictionary.

Sum for Nested Dictionary Values with Identical Keys

In this approach we will add those values which are having identical keys in the nested dictionary.

Algorithm

  • Step 1 − Initialize the nested dictionary as the_nested_dict.

  • Step 2 − Then we will initialize the empty dictionary to store the sum values with the identical keys.

  • Step 3 − Then the loop will be initiated for the values of the_nested_dict.

  • Step 4 − Inside the outer loop we will initiate another inner loop over the sub dictionary items.

  • Step 5 − Then inside the inner loop the current item value will be added to the respective key in the sum_values dictionary.

  • Step 6 − The updated sum_values dictionary is printed with the help of print() function.

  • Step 7 − The execution of the program is complete.

Example

# Initialize the nested dictionary
the_nested_dict = {
   'apple' : {'red' : 4, 'yellow' : 5, 'green' : 8},
   'guava' : {'red' : 8, 'white' : 10},
   'banana' : {'yellow' : 19, 'green' : 10}
}

#Initialize the empty dictionary
sum_values = dict()
for subdict in the_nested_dict.values():
   for key, elem in subdict.items():
      sum_values[key] = elem + sum_values.get(key, 0)

#Show the summation of nested dictionary values with same key
print("The summation values : " + str(sum_values))

Output

The summation values : {'red': 12, 'yellow': 24, 'green': 18, 'white': 10}

Complexity

If N is the number of key-value pairs in the main dictionary and M is the number of key-value pairs in the nested dictionary then the time complexity is O(NM). Reason for this is that we are iterating the nested dictionary for every main dictionary.

Conclusion

So far, we have seen two methods for solving these kinds of problems. First we added up all the values present in the nested dictionary and second we summed up only the identical or same key values.

Updated on: 16-Oct-2023

224 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements