Python: Sum all the items in a dictionary
10. Sum All Items in a Dictionary
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
For more Practice: Solve these Related Problems:
- Write a Python program to calculate the sum of all values in a dictionary where values are numbers.
- Write a Python program to use a for-loop to iterate over dictionary values and compute their total sum.
- Write a Python program to implement a function that returns the sum of the items of a dictionary using the sum() function.
- Write a Python program to combine values of a dictionary with a reduce() function to compute their sum.
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.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics