Last updated: Apr 9, 2024
Reading timeยท5 min
Use the sum()
function to sum all values in a dictionary.
The values()
method on the dictionary will return a view of the dictionary's
values, which can directly be passed to the sum()
function to get the sum.
my_dict = { 'one': 1, 'two': 2, 'three': 3, } total = sum(my_dict.values()) print(total) # ๐๏ธ 6 # ๐๏ธ [1, 2, 3] print(list(my_dict.values()))
We used the sum()
function to sum all values in a dictionary.
The dict.values() method returns a new view of the dictionary's values.
The sum() function takes an iterable, sums its items from left to right and returns the total.
print(sum([1, 2, 3])) # ๐๏ธ 6
The sum
function takes the following 2 arguments:
Name | Description |
---|---|
iterable | the iterable whose items to sum |
start | sums the start value and the items of the iterable. sum defaults to 0 (optional) |
Notice that the value for the optional start
argument defaults to 0
. This
means that using this approach with an empty dictionary would return 0
.
my_dict = {} total = sum(my_dict.values()) print(total) # ๐๏ธ 0 # ๐๏ธ [] print(list(my_dict.values()))
Alternatively, you can use a for loop.
for
loopThis is a three-step process:
0
.for
loop to iterate over the dictionary's values.my_dict = { 'one': 1, 'two': 2, 'three': 3, } total = 0 for value in my_dict.values(): total += value print(total) # ๐๏ธ 6
We initialized the total
variable to 0
and used the dict.values()
method
to get an iterator of the dictionary's values.
On each iteration, we reassign the total
variable to the result of adding the
current value to it.
You can also sum all values in a dictionary using the reduce()
function.
from functools import reduce my_dict = { 'one': 1, 'two': 2, 'three': 3, } total = reduce( lambda acc, current: acc + current, my_dict.values() ) print(total) # ๐๏ธ 6
Using the reduce()
function is definitely not needed in this scenario as it is
much more verbose than passing the view of the dictionary's values directly to
the sum()
function.
The reduce() function takes the following 3 parameters:
Name | Description |
---|---|
function | A function that takes 2 parameters - the accumulated value and a value from the iterable. |
iterable | Each element in the iterable will get passed as an argument to the function. |
initializer | An optional initializer value that is placed before the items of the iterable in the calculation. |
lambda
function in the example takes the accumulated value and the current value as parameters and returns the sum of the two.If we provide a value for the initializer
argument, it is placed before the
items of the iterable in the calculation.
from functools import reduce my_dict = { 'one': 1, 'two': 2, 'three': 3, } total = reduce( lambda acc, current: acc + current, my_dict.values(), 0 ) print(total) # ๐๏ธ 6
In the example, we passed 0
for the initializer argument, so the value of the
accumulator
will be 0
on the first iteration.
The value of the accumulator
would get set to the first element in the
iterable if we didn't pass a value for the initializer
.
If the iterable
is empty and the initializer
is provided, the initializer
is returned.
from functools import reduce my_dict = {} total = reduce( lambda acc, current: acc + current, my_dict.values(), 0 ) print(total) # ๐๏ธ 0
To sum the values in a list of dictionaries:
sum()
function.from collections import Counter # โ Sum the values in a list of dictionaries for a specific `dict` key list_of_dicts = [ {'name': 'Alice', 'salary': 100}, {'name': 'Bob', 'salary': 100}, {'name': 'Carl', 'salary': 100}, ] total = sum(d['salary'] for d in list_of_dicts) print(total) # ๐๏ธ 300
We used a generator expression to iterate over the list of dictionaries.
On each iteration, we access the specific dict
key to get the corresponding
value and return the result.
The sum() function takes an iterable, sums its items from left to right and returns the total.
The sum
function takes the following 2 arguments:
Name | Description |
---|---|
iterable | the iterable whose items to sum |
start | sums the start value and the items of the iterable. sum defaults to 0 (optional) |
If you need to sum the values in a list of dictionaries for all dictionary keys,
use the Counter
class.
from collections import Counter list_of_dicts = [ {'id': 1, 'salary': 100}, {'id': 2, 'salary': 100}, {'id': 3, 'salary': 100}, ] my_dict = Counter() for d in list_of_dicts: for key, value in d.items(): my_dict[key] += value # ๐๏ธ Counter({'salary': 300, 'id': 6}) print(my_dict) total = sum(my_dict.values()) print(total) # ๐๏ธ 306
The
Counter
class from the collections
module is a subclass of the dict
class.
The class is basically a mapping of key-count pairs.
The outer for
loop in the example iterates over the list of dictionaries.
The inner loop iterates over the items of the current dictionary.
The dict.items method returns a new view of the dictionary's items ((key, value) pairs).
list_of_dicts = [ {'id': 1, 'salary': 100}, {'id': 2, 'salary': 100}, {'id': 3, 'salary': 100}, ] # ๐๏ธ dict_items([('id', 1), ('salary', 100)]) print(list_of_dicts[0].items())
On each iteration of one of the nested dictionaries, we update the key-count
pair in the central Counter
object.
Here is the complete code snippet.
from collections import Counter list_of_dicts = [ {'id': 1, 'salary': 100}, {'id': 2, 'salary': 100}, {'id': 3, 'salary': 100}, ] my_dict = Counter() for d in list_of_dicts: for key, value in d.items(): my_dict[key] += value # ๐๏ธ Counter({'salary': 300, 'id': 6}) print(my_dict) total = sum(my_dict.values()) print(total) # ๐๏ธ 306