Given a nested dictionary and we have to find sum of particular value in that nested dictionary. This is basically useful in cases where we are given a JSON object or we have scraped a particular page and we want to sum the value of a particular attribute in objects.
Code #1: Find sum of sharpness values using sum() function
Step-by-step approach:
- Use a generator expression with the sum() function to find the sum of all the ‘sharpness‘ values in the nested dictionary.
a. Iterate over the dictionary’s values using the values() method.
b. Filter out the non-dictionary values using a conditional statement.
c. Extract the ‘sharpness‘ value from each dictionary using the key. - Assign the result to the ‘sumValue1‘ variable.
- Use a generator expression with the sum() function to find the sum of all the ‘steel‘ values in the nested dictionary.
a. Iterate over the dictionary’s values using the values() method.
b. Filter out the non-dictionary values using a conditional statement.
c. Extract the ‘steel‘ value from each dictionary using the key. - Assign the result to the ‘sumValue2‘ variable.
- Print the ‘sumValue1‘ and ‘sumValue2‘ variables.
Below is the implementation of the above approach:
Python3
# Python code to find sum values within nested dictionaries weapons = {' ': None, ' sword ': { ' steel': 151 , 'sharpness' : 100 , 'age' : 2 ,}, 'arrow' : { 'steel' : 120 , 'sharpness' : 205 , 'age' : 1 ,}} sumValue1 = sum (d[ 'sharpness' ] for d in weapons.values() if d) sumValue2 = sum (d[ 'steel' ] for d in weapons.values() if d) print (sumValue1) print (sumValue2) |
305 271
Time complexity: O(N)
Auxiliary space: O(1)
Code #2: Using Iteration to convert it into key:value pair.
Python3
# Python code to find sum values within nested dictionaries weapons = {' ': None, ' sword ': { ' steel': 151 , 'sharpness' : 100 , 'age' : 2 ,}, 'arrow' : { 'steel' : 120 , 'sharpness' : 205 , 'age' : 1 ,}} sum = 0 # iterating key value pair for key ,value in weapons.items(): if value and 'sharpness' in value.keys(): # Adding value of sharpness to sum sum + = value[ 'sharpness' ] # printing sum print ( sum ) |
305
Time complexity: O(n), where n is the total number of keys in the nested dictionary.
Auxiliary space: O(1) because the memory used by the program does not increase with the size of the input, and it only uses a constant amount of extra space to store the sum variable.