Open In App

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

Last Updated : 26 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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.

 



Similar Reads

Python Program to find the profit or loss when CP of N items is equal to SP of M items
Given [Tex]N   [/Tex]and [Tex]M   [/Tex]denoting that the Cost Price of N articles is equal to the Selling Price of M articles. The task is to determine the profit or Loss percentage. Examples:  Input: N = 8, M = 9 Output: Loss = -11.11% Input: N = 8, M = 5 Output: Profit = 60% Formula:-  Below is the implementation of the above approach: C/C++ Cod
1 min read
Python program to multiply all the items in a dictionary
Python program to illustrate multiplying all the items in a dictionary could be done by creating a dictionary that will store all the key-value pairs, multiplying the value of all the keys, and storing it in a variable. Example: Input: dict = {'value1':5, 'value2':4, 'value3':3, 'value4':2, 'value5':1} Output: ans = 120 Input: dict = {'v1':10, 'v2'
2 min read
Python - All possible items combination dictionary
Sometimes, while working with data, we can have a problem in which we are provided with sample data of key and value list and we require to construct actual data as all possible combination of keys and value list of similar size. Lets discuss certain ways in which this task can be performed. Method #1 : Using loop + set() The combination of above f
4 min read
Python program to convert URL Parameters to Dictionary items
Given URL Parameters string, convert to dictionary items. Input : test_str = 'gfg=4&is=5' Output : {'gfg': ['4'], 'is': ['5']} Explanation : gfg's value is 4. Input : test_str = 'gfg=4' Output : {'gfg': ['4']} Explanation : gfg's value is 4 as param. Method #1 : Using urllib.parse.parse_qs() This is default inbuilt function which performs this
5 min read
Python program to extract dictionary items for custom values
Given a dictionary, extract all the items that match given values in the list Example: Input : test_dict = {"Gfg" : 3, "is" : 5, "for" : 8, "Geeks" : 10, "Best" : 16 }, sub_list = [5, 4, 10, 20, 16, 8] Output : {'is': 5, 'Geeks': 10, 'Best': 16, "for" : 8} Explanation : All values matching list values extracted along with keys. Input : test_dict =
4 min read
Python Program to create a sub-dictionary containing all keys from dictionary list
Given the dictionary list, our task is to create a new dictionary list that contains all the keys, if not, then assign None to the key and persist of each dictionary. Example: Input : test_list = [{'gfg' : 3, 'is' : 7}, {'gfg' : 3, 'is' : 1, 'best' : 5}, {'gfg' : 8}]Output : [{'is': 7, 'best': None, 'gfg': 3}, {'is': 1, 'best': 5, 'gfg': 3}, {'is':
8 min read
Sum all Items in Python List without using sum()
In Python, summing all the elements of a list is a common task, and while the `sum()` function simplifies the process, you can also implement the summation manually using a loop. By iterating through each element in the list and accumulating the total, you can achieve the same result without relying on the built-in `sum()` function. This alternativ
3 min read
Python Dictionary items() method
Dictionary in Python is an unordered collection of data values, used to store data values like a map, which unlike other Data Types that hold only single value as an element, Dictionary holds key : value pair.In Python Dictionary, items() method is used to return the list with all dictionary keys with values. Syntax: dictionary.items()Parameters: T
2 min read
Python | Delete items from dictionary while iterating
A dictionary in Python is an ordered collection of data values. Unlike other Data Types that hold only a single value as an element, a dictionary holds the key: value pairs. Dictionary keys must be unique and must be of an immutable data type such as a: string, integer or tuple. Note: In Python 2 dictionary keys were unordered. As of Python 3, they
3 min read
Python | Count number of items in a dictionary value that is a list
In Python, dictionary is a collection which is unordered, changeable and indexed. Dictionaries are written with curly brackets, and they have keys and values. It is used to hash a particular key. A dictionary has multiple key:value pairs. There can be multiple pairs where value corresponding to a key is a list. To check that the value is a list or
5 min read
three90RightbarBannerImg