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
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)
|
Time complexity: O(N)
Auxiliary space: O(1)
Code #2: Using Iteration to convert it into key:value pair.
Python3
weapons = {' ': None, ' sword ': { ' steel': 151 ,
'sharpness' : 100 ,
'age' : 2 ,},
'arrow' : { 'steel' : 120 ,
'sharpness' : 205 ,
'age' : 1 ,}}
sum = 0
for key ,value in weapons.items():
if value and 'sharpness' in value.keys():
sum + = value[ 'sharpness' ]
print ( sum )
|
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.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
29 Mar, 2023
Like Article
Save Article