Progress

Python Program to find Sum of all Values in Dictionary

Python Program to find Sum of all Values in Dictionary

Dictionary is an important data structure of Python which contains key-value pairs. The values are not accessible with normal index (like a list) but with their keys. Here is the optimized Python program to find the sum of all values in a dictionary.

Python Program: Sum of dictionary values using the sum function

This is the simplest one-line solution to find the total sum of values in any Python dictionary.

Copy
myDict = {'a': 1, 'b': 2, 'c': 3}
total = sum(myDict.values())
print("The sum of all items in dictionary is {}".format(total))
Output
The sum of all items in dictionary is 6

At the very first line, we declared a dictionary.

The second line contains the logic of the code. The values() method of dictionary returns an iterable of type dict_values which contains the values of that dictionary.

The sum() function takes an iterable as an argument and returns the total sum of all its elements.

Finally, we print the resulting sum of all values in the dictionary.

Python Program: Find the Sum of dictionary using for loop

Copy
myDict = {'a': 1, 'b': 2, 'c': 3}
total = 0
for i in myDict.values():
    total+=i
print("The sum of all items in dictionary is {}".format(total))
Output
The sum of all items in dictionary is 6

The logic of this Python code is to loop through the dictionary values and find the sum of all items in the dictionary.

The above code has features that may be Python-specific but the code below is suited for almost all programming languages.

This approach is useful to find the sum of all items of any dictionary or key-value pair.

Copy
myDict = {'a': 1, 'b': 2, 'c': 3}
total = 0
for i in myDict:
    total+=myDict[i]
print("The sum of all items in dictionary is {}".format(total))
Output
The sum of all items in dictionary is 6

The dictionary values can be accessed by their keys. The for loop iterate through the dictionary keys add the values to the total variable.

Here is a short demonstration of how to get dictionary values in Python.

Copy
myDict = {'a': 1, 'b': 2, 'c': 3}
myDict['a']
myDict['b']
myDict['c']
Output
1
2
3

Related Python Examples:

Share the Post ;)

Related Posts