Python Program to find sum of all items in a dictionary


April 4, 2022, Learn eTutorial
1148

In this simple python program, we need to find sum of all items in a dictionary. It is a number-based python program.

For a better understanding of this example, we always recommend you to learn the basic topics of Python programming listed below:

What is a dictionary in python?

In this simple python program, we need to find the sum of all the dictionary elements. A dictionary is a collection of values that is unordered and has a key and value pair. We use the dictionary to retrieve the values when we know the key easily. We can add the elements into a python dictionary using the braces. We put the elements in the braces with a comma. Every element in the dictionary has a key and value associated with the key, represented as a key-value pair. 

Values may be of any value or any type which may be a repeat or not, but for a key, it must not be a repeat, and it must be a tuple, number, or string.

How to find the sum of dictionary values?

In this dictionary python program, we need to find the sum of all the dictionary elements. For that, we have to accept a dictionary with some predefined values in it. Then we use the sum method in python to get the sum of elements in the dictionary. Finally, we are printing the sum using the print function in python.

The sum(): The sum function in python adds the elements or the iterables and does the sum and returns the final result. Here we are using the sum function with the dictionary values, and we get the result from the sum function. The syntax of the sum function is sum(iterable, start).

ALGORITHM

STEP 1: Initialize the dictionary with some predefined values in it.

STEP 2: Use the sum function in python to get the sum of the value of the dictionary elements.

STEP 3: Display the sum using the print function in the python language.

Python Source Code

                                          d={'A':100,'B':540,'C':239}
print("Sum of values of the dictionary:")
print(sum(d.values()))
                                      

OUTPUT

Sum of values of the dictionary:
879