w3resource

Python: Sum all the items in a dictionary

Python dictionary: Exercise-10 with Solution

Write a Python program to sum all the items in a dictionary.

Sample Solution:

Python Code:

# Create a dictionary 'my_dict' with key-value pairs.
my_dict = {'data1': 100, 'data2': -54, 'data3': 247}
# Use the 'sum' function to calculate the sum of all values in the 'my_dict' dictionary.
# 'my_dict.values()' extracts the values from the dictionary, and 'sum' calculates their sum.
result = sum(my_dict.values())
# Print the result, which is the sum of the values.
print(result) 

Sample Output:

293 

Python Code Editor:

Previous: Write a Python program to iterate over dictionaries using for loops.
Next: Write a Python program to multiply all the items in a dictionary.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.