Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Finding the Summation of Nested Dictionary Values in Python
Sometimes we need to sum up values in nested dictionaries. In this article, we'll explore different approaches to find the summation of nested dictionary values using Python.
Understanding the Problem
A nested dictionary is a dictionary that contains other dictionaries as values. Our goal is to find and sum all numeric values within these nested structures. This is useful for aggregating data in hierarchical formats like JSON or configuration files.
Method 1: Sum All Nested Dictionary Values
This approach recursively traverses the nested dictionary and sums all numeric values it encounters ?
Algorithm
Step 1 Define a function that takes a nested dictionary as input
Step 2 Initialize a sum variable to store the total
Step 3 Iterate through all values in the dictionary
Step 4 If a value is numeric, add it to the sum
Step 5 If a value is another dictionary, recursively call the function
Step 6 Return the total sum
Example
# Function to get the summation of all values
def summation_values(the_dictionary):
total_sum = 0
for value in the_dictionary.values():
if isinstance(value, int):
total_sum += value
elif isinstance(value, dict):
total_sum += summation_values(value)
return total_sum
# Input nested dictionary
nested_dict = {
'apple': 10,
'banana': {
'cucumber': 12,
'pineapple': {
'orange': 23,
'mango': 14
}
},
'guava': 16
}
# Calculate the sum
result = summation_values(nested_dict)
print("The summation of nested dictionary values:", result)
The summation of nested dictionary values: 75
Complexity
The time complexity is O(N), where N is the total number of key-value pairs across all nested levels. The space complexity is O(D) due to recursion depth D.
Method 2: Sum Values with Identical Keys
This approach groups values by their keys across different sub-dictionaries and sums values that share the same key name ?
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 empty dictionary to store sums
sum_values = {}
# Iterate through each sub-dictionary
for subdict in the_nested_dict.values():
for key, value in subdict.items():
sum_values[key] = value + sum_values.get(key, 0)
# Display results
print("The summation values:", sum_values)
The summation values: {'red': 12, 'yellow': 24, 'green': 18, 'white': 10}
Complexity
The time complexity is O(N × M), where N is the number of main dictionary entries and M is the average number of key-value pairs in sub-dictionaries.
Method 3: Using Collections.defaultdict
We can simplify the identical keys approach using defaultdict ?
from collections import defaultdict
# Initialize the nested dictionary
the_nested_dict = {
'fruits': {'apple': 5, 'banana': 3},
'vegetables': {'carrot': 2, 'apple': 1}, # 'apple' appears again
'grains': {'rice': 10, 'banana': 2} # 'banana' appears again
}
# Use defaultdict to automatically initialize missing keys
sum_values = defaultdict(int)
for subdict in the_nested_dict.values():
for key, value in subdict.items():
sum_values[key] += value
# Convert back to regular dict and display
result = dict(sum_values)
print("Summation using defaultdict:", result)
Summation using defaultdict: {'apple': 6, 'banana': 5, 'carrot': 2, 'rice': 10}
Comparison
| Method | Use Case | Time Complexity | Best For |
|---|---|---|---|
| Recursive Sum | Sum all values | O(N) | Deep nested structures |
| Identical Keys | Group by key names | O(N × M) | Data aggregation |
| defaultdict | Group by key names | O(N × M) | Cleaner syntax |
Conclusion
Use recursive summation when you need the total of all values in nested dictionaries. Use the identical keys approach when you want to group and sum values by their key names across different sub-dictionaries.
