Python program to find the sum of all items in a dictionary
|In this Python example, we will explore multiple ways to find the sum of all items in a dictionary.
Some of the topics which will be helpful for understanding the program implementation better are:
1. Using a Loop
One way to find the sum of all items in a dictionary is by using a loop. We can iterate over the values of the dictionary and add them to a variable to keep track of the sum.
my_dict = {'a': 1, 'b': 2, 'c': 3} sum_values = 0 for value in my_dict.values(): sum_values += value print("Sum of all items in the dictionary:", sum_values)
Output Sum of all items in the dictionary: 6
2. Using the sum()
Function
Another way to find the sum of all items in a dictionary is by using the sum()
function. We can pass the values of the dictionary to the sum()
function to get the sum of all items in the dictionary.
Here’s an example:
my_dict = {'a': 1, 'b': 2, 'c': 3} sum_values = sum(my_dict.values()) print("Sum of all items in the dictionary:", sum_values)
Output Sum of all items in the dictionary: 6
3. Using List Comprehension
We can also use list comprehension to find the sum of all items in a dictionary. We can create a list of values from the dictionary using list comprehension and then pass the list to the sum()
function.
This is very useful when we have to perform some operations on the value before doing the sum. For example in the program below we will multiply the number by 10 before calculating the sum.
my_dict = {'a': 1, 'b': 2, 'c': 3} sum_values = sum([value*10 for value in my_dict.values()]) print("Sum of all items in the dictionary:", sum_values)
Output Sum of all items in the dictionary: 60
4. Conclusion
In this article, we have discussed three different ways to find the sum of all items in a dictionary.
Helpful Links
Please follow the Python tutorial series or the menu in the sidebar for the complete tutorial series.
Also for examples in Python and practice please refer to Python Examples.
Complete code samples are present on Github project.
Recommended Books
An investment in knowledge always pays the best interest. I hope you like the tutorial. Do come back for more because learning paves way for a better understanding
Do not forget to share and Subscribe.
Happy coding!! ?