How to Sum Dictionary Values in Python
This guide explores various methods for summing numeric values stored within Python dictionaries. We'll cover summing all values in a single dictionary, summing values for specific keys across a list of dictionaries, and summing all numeric values across all keys in a list of dictionaries. Techniques include using the built-in sum()
, for
loops, functools.reduce
, and collections.Counter
.
Summing All Values in a Single Dictionary
To calculate the total sum of all numeric values within a single dictionary:
Using sum()
with dict.values()
(Recommended)
This is the most concise and Pythonic approach:
my_dict = {'one': 1, 'two': 2, 'three': 3}
total = sum(my_dict.values())
print(total) # Output: 6
my_dict.values()
returns a view object containing all the values from the dictionary.sum()
directly iterates over this view and calculates the sum.- This method correctly returns
0
for an empty dictionary.
Using a for
Loop
A for
loop provides a more explicit way to achieve the same result:
my_dict = {'one': 1, 'two': 2, 'three': 3}
total = 0
for value in my_dict.values():
total += value
print(total) # Output: 6
Using functools.reduce()
While reduce()
can be used, it's generally considered less readable than sum()
for simple summation:
from functools import reduce
my_dict = {'one': 1, 'two': 2, 'three': 3}
total = reduce(lambda acc, current: acc + current, my_dict.values(), 0) # Start with 0
print(total) # Output: 6
- The
reduce()
function takes a function and applies it cumulatively to the items of an iterable.
Summing Values for a Specific Key in a List of Dictionaries
To sum the values associated with a specific key across all dictionaries in a list:
list_of_dicts = [
{'name': 'Alice', 'salary': 100},
{'name': 'Bob', 'salary': 150},
{'name': 'Carl', 'salary': 120},
{'name': 'Diana', 'score': 95}, # Dictionary might not have 'salary'
]
# Sum only the 'salary' values
total_salary = sum(d.get('salary', 0) for d in list_of_dicts) # Use get() for safety
print(total_salary) # Output: 370
- The generator expression
(d.get('salary', 0) for d in list_of_dicts)
iterates through the list. d.get('salary', 0)
safely retrieves the value for the 'salary' key. If the key doesn't exist in a dictionary, it returns the default value0
, preventingKeyError
and ensuring those dictionaries don't affect the sum.sum()
adds up the retrieved salary values.
Summing Values for All Keys in a List of Dictionaries
To sum values grouped by their respective keys across a list of dictionaries, use collections.Counter
:
from collections import Counter
list_of_dicts = [
{'id': 1, 'salary': 100, 'bonus': 10},
{'id': 2, 'salary': 150},
{'id': 3, 'salary': 120, 'bonus': 20},
]
totals_by_key = Counter()
for d in list_of_dicts:
for key, value in d.items():
# Only add if the value is numeric (int or float)
if isinstance(value, (int, float)):
totals_by_key[key] += value
print(totals_by_key)
# Output: Counter({'salary': 370, 'bonus': 30, 'id': 6})
# Optional: Get the grand total of all numeric values
grand_total = sum(totals_by_key.values())
print(grand_total) # Output: 406
Counter()
is a dictionary subclass designed for counting hashable objects (or, in this case, accumulating sums).- The nested loops iterate through each dictionary and then each key-value pair.
isinstance(value, (int, float))
ensures we only try to sum numeric types.totals_by_key[key] += value
adds the value to the running total for that specific key in theCounter
.
Conclusion
This guide explored various methods for summing values in Python dictionaries.
- For summing all values in a single dictionary,
sum(my_dict.values())
is the most direct approach. - When summing values for a specific key across a list of dictionaries, a generator expression with
sum()
anddict.get()
is recommended for safety and conciseness. - For summing all numeric values grouped by key across a list of dictionaries,
collections.Counter
provides an effective solution.