Python program to find the sum of all items in a dictionary
Last Updated :
26 Apr, 2023
Given a dictionary in Python, write a Python program to find the sum of all items in the dictionary.
Examples:
Input : {‘a’: 100, ‘b’:200, ‘c’:300}
Output : 600
Input : {‘x’: 25, ‘y’:18, ‘z’:45}
Output : 88
Method #1: Using Inbuilt sum() Function
Use the sum function to find the sum of dictionary values.
Python3
def returnSum(myDict):
list = []
for i in myDict:
list .append(myDict[i])
final = sum ( list )
return final
dict = { 'a' : 100 , 'b' : 200 , 'c' : 300 }
print ( "Sum :" , returnSum( dict ))
|
Output:
Sum : 600
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #2: Using For loop to iterate through values using values() function
Iterate through each value of the dictionary using values() function and keep adding it to the sum.
Python3
def returnSum( dict ):
sum = 0
for i in dict .values():
sum = sum + i
return sum
dict = { 'a' : 100 , 'b' : 200 , 'c' : 300 }
print ( "Sum :" , returnSum( dict ))
|
Output:
Sum : 600
Method #3: Using for loop to iterate over each value in a dictionary
Iterate through each item of the dictionary and simply keep adding the values to the sum variable.
Python3
def returnSum( dict ):
sum = 0
for i in dict :
sum = sum + dict [i]
return sum
dict = { 'a' : 100 , 'b' : 200 , 'c' : 300 }
print ( "Sum :" , returnSum( dict ))
|
Output:
Sum : 600
Method #4: Using values() and sum() function
Here we are using the dictionary.sum() method to find the sum of values taken out through dictionary.values() function
Step by step approach :
- We define a function called returnSum that takes a single argument, which is a dictionary.
- The returnSum function uses the sum() function to add up all the values in the dictionary.
- The returnSum function returns the sum of the dictionary values.
- We define a dictionary called dict with three key-value pairs.
- We call the returnSum function with the dict dictionary as an argument.
- The returnSum function returns the sum of the values in the dict dictionary.
- We print the resulting sum of the values in the dict dictionary using the print() function.
Python3
def returnSum( dict ):
return sum ( dict .values())
dict = { 'a' : 100 , 'b' : 200 , 'c' : 300 }
print ( "Sum :" , returnSum( dict ))
|
Output:
Sum : 600
Time complexity: O(n), where n is the number of key-value pairs in the dictionary, since we need to iterate over all the values in the dictionary to compute the sum.
Auxiliary space: O(1), since we are only storing a single integer value for the sum.
Method #5:
Using the lambda function
The lambda function is used to calculate the summation of all the values in the dictionary
Python3
import functools
dic = { 'a' : 100 , 'b' : 200 , 'c' : 300 }
sum_dic = functools. reduce ( lambda ac,k: ac + dic[k], dic, 0 )
print ( "Sum :" , sum_dic)
|
Output:
Sum : 600
The time complexity of this program is O(n), where n is the number of key-value pairs in the dictionary.
The auxiliary space complexity is O(1), as we only need to store a constant number of variables in memory: the accumulator (ac), the current key (k), and the initial value for the accumulator (0).
Method #6: Using a generator expression and the built-in sum function
Another approach to find the sum of all items in a dictionary is to use a generator expression and the built-in sum function. A generator expression is an expression that generates a sequence of values, and is similar to a list comprehension, but does not create a new list.
For example:
Python3
def returnSum(myDict):
return sum (myDict[key] for key in myDict)
dict = { 'a' : 100 , 'b' : 200 , 'c' : 300 }
print ( "Sum :" , returnSum( dict ))
|
Time complexity: O(n), where n is the number of items in the dictionary, since it involves iterating through the dictionary to generate the sequence of values.
Auxiliary space: O(n), since it generates a sequence of values that is the same size as the original dictionary.
Method #7: Using the reduce() function
Step-by-step approach:
- Import the functools module to use the reduce() function.
- Define a function named “sum_dict_values” that takes a dictionary as its argument.
- Use the reduce() function to add up all the values in the dictionary.
- Return the final sum value.
- Call the function with the dictionary as the argument and print the result.
Below is the implementation of the above approach:
Python3
import functools
def sum_dict_values( dict ):
return functools. reduce ( lambda acc, x: acc + dict [x], dict , 0 )
dict = { 'a' : 100 , 'b' : 200 , 'c' : 300 }
print ( "Sum :" , sum_dict_values( dict ))
|
Time complexity: O(n), where n is the number of items in the dictionary.
Auxiliary space: O(1), as we are not using any extra data structure to store intermediate values.
Method #8: Using numpy:
Algorithm:
- Define a function returnSum that takes a dictionary as input.
- Convert the dictionary values to a list using the list() function.
- Convert the list to a NumPy array using the np.array() function.
- Use the np.sum() function to find the sum of the array.
- Return the sum.
- In the driver code, initialize a dictionary with the given values.
- Call the returnSum() function with the dictionary as input and print the result.
Python3
import numpy as np
def returnSum( dict ):
values = np.array( list ( dict .values()))
return np. sum (values)
dict = { 'a' : 100 , 'b' : 200 , 'c' : 300 }
print ( "Sum:" , returnSum( dict ))
|
Output:
Sum: 600
Time complexity:
The time complexity is O(n), where n is the number of items in the dictionary. The list() function takes O(n) time to convert the dictionary values to a list, and the np.array() function takes O(n) time to convert the list to a NumPy array. The np.sum() function takes O(1) time to find the sum of the array.
Space complexity:
The space complexity is O(n), where n is the number of items in the dictionary. This is because we need to store the dictionary values in a list, which has a maximum length of n. We also need to store the NumPy array, which has the same length as the list. The space complexity of the dictionary and the returned sum is not included in the analysis.
Please Login to comment...