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
Selected Reading
How to sum values of a Python dictionary?
It is pretty easy to get the sum of values of a Python dictionary. You can first get the values in a list using the dict.values(). Then you can call the sum method to get the sum of these values.
Example
Here's how to sum dictionary values using the sum() function ?
d = {
'foo': 10,
'bar': 20,
'baz': 30
}
print(sum(d.values()))
This will give the output ?
60
Using List Comprehension
You can also sum dictionary values using list comprehension ?
scores = {'Alice': 85, 'Bob': 92, 'Charlie': 78}
total = sum([value for value in scores.values()])
print(total)
255
Summing Based on Conditions
To sum only values that meet certain criteria ?
prices = {'apple': 2.5, 'banana': 1.2, 'orange': 3.0, 'grape': 4.5}
# Sum only prices greater than 2
expensive_total = sum(price for price in prices.values() if price > 2)
print(f"Total for expensive items: ${expensive_total}")
Total for expensive items: $10.0
Handling Mixed Data Types
When dictionary contains non-numeric values, filter them first ?
mixed_data = {'count': 15, 'name': 'John', 'score': 88, 'active': True}
# Sum only numeric values
numeric_sum = sum(value for value in mixed_data.values() if isinstance(value, (int, float)))
print(f"Sum of numeric values: {numeric_sum}")
Sum of numeric values: 103
Conclusion
Use sum(dict.values()) for simple dictionary value summation. For conditional summation, combine sum() with generator expressions or list comprehension.
Advertisements
