Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python program to find the sum of all items in a dictionary
In this article, we will learn different approaches to calculate the sum of all values in a dictionary. Python provides several methods to iterate through dictionary values and compute their total.
Problem statement ? We are given a dictionary, and we need to calculate the sum of all its values.
Here are four effective approaches to solve this problem ?
Method 1: Using Dictionary Items Iteration
This approach iterates through dictionary items and accesses values using keys ?
# sum function
def calculate_sum(my_dict):
total = 0
for key in my_dict:
total = total + my_dict[key]
return total
# Driver Function
data = {'A': 10, 'B': 20, 'C': 30, 'D': 40}
print("Sum of dictionary values:", calculate_sum(data))
Sum of dictionary values: 100
Method 2: Using Dictionary Values() Method
This approach directly iterates through dictionary values using the values() method ?
# sum function
def calculate_sum(my_dict):
total = 0
for value in my_dict.values():
total = total + value
return total
# Driver Function
data = {'A': 10, 'B': 20, 'C': 30, 'D': 40}
print("Sum of dictionary values:", calculate_sum(data))
Sum of dictionary values: 100
Method 3: Using Dictionary Keys() Method
This approach iterates through dictionary keys and accesses values using key indexing ?
# sum function
def calculate_sum(my_dict):
total = 0
for key in my_dict.keys():
total = total + my_dict[key]
return total
# Driver Function
data = {'A': 10, 'B': 20, 'C': 30, 'D': 40}
print("Sum of dictionary values:", calculate_sum(data))
Sum of dictionary values: 100
Method 4: Using Built-in sum() Function
The most Pythonic approach uses the built-in sum() function with values() ?
# Using built-in sum function
data = {'A': 10, 'B': 20, 'C': 30, 'D': 40}
total = sum(data.values())
print("Sum of dictionary values:", total)
Sum of dictionary values: 100
Comparison
| Method | Readability | Performance | Best For |
|---|---|---|---|
| Items iteration | Good | Medium | When you need both keys and values |
| values() iteration | Good | Fast | Direct access to values |
| keys() iteration | Good | Medium | When you need key-based logic |
| Built-in sum() | Excellent | Fastest | Simple sum calculations |
Conclusion
The built-in sum() function with values() is the most efficient and readable approach. Use manual iteration methods when you need additional processing logic during summation.
