Friday, December 27, 2024
Google search engine
HomeLanguagesPython program to find the sum of all items in a dictionary

Python program to find the sum of all items in a dictionary

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




# Python3 Program to find sum of
# all items in a Dictionary
 
# Function to print sum
 
 
def returnSum(myDict):
 
    list = []
    for i in myDict:
        list.append(myDict[i])
    final = sum(list)
 
    return final
 
 
# Driver Function
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




# Python3 Program to find sum of
# all items in a Dictionary
 
# Function to print sum
 
 
def returnSum(dict):
 
    sum = 0
    for i in dict.values():
        sum = sum + i
 
    return sum
 
 
# Driver Function
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




# Python3 Program to find sum of
# all items in a Dictionary
 
# Function to print sum
 
 
def returnSum(dict):
 
    sum = 0
    for i in dict:
        sum = sum + dict[i]
 
    return sum
 
 
# Driver Function
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 : 

  1. We define a function called returnSum that takes a single argument, which is a dictionary.
  2. The returnSum function uses the sum() function to add up all the values in the dictionary.
  3. The returnSum function returns the sum of the dictionary values.
  4. We define a dictionary called dict with three key-value pairs.
  5. We call the returnSum function with the dict dictionary as an argument.
  6. The returnSum function returns the sum of the values in the dict dictionary.
  7. We print the resulting sum of the values in the dict dictionary using the print() function.

Python3




# Python3 Program to find sum of
# all items in a Dictionary
 
# Function to print sum
 
 
def returnSum(dict):
    return sum(dict.values())
 
 
# Driver Function
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))
 
#This code is contributed by Edula Vinay Kumar Reddy


Output

Sum : 600

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)
 
# Driver Function
dict = {'a': 100, 'b': 200, 'c': 300}
print("Sum :", sum_dict_values(dict))


Output

Sum : 600

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:

  1. Define a function returnSum that takes a dictionary as input.
  2. Convert the dictionary values to a list using the list() function.
  3. Convert the list to a NumPy array using the np.array() function.
  4. Use the np.sum() function to find the sum of the array.
  5. Return the sum.
  6. In the driver code, initialize a dictionary with the given values.
  7. Call the returnSum() function with the dictionary as input and print the result.

Python3




import numpy as np
 
# function to return sum
def returnSum(dict):
    # convert dict values to a NumPy array
    values = np.array(list(dict.values()))
    # return the sum of the values
    return np.sum(values)
 
# driver code
dict = {'a': 100, 'b': 200, 'c': 300}
print("Sum:", returnSum(dict))
#this code is contributed by Jyothi pinjala.


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.

 

RELATED ARTICLES

Most Popular

Recent Comments