How to sum all the values in a dictionary?

2019-01-10 02:33发布

Let's say I have a dictionary in which the keys map to integers like:

d = {'key1': 1,'key2': 14,'key3': 47}

Is there a syntactically minimalistic way to return the sum of the values in d—i.e. 62 in this case?

5条回答
叛逆
2楼-- · 2019-01-10 02:47

I feel sum(d.values()) is the most efficient way to get the sum.

You can also try the reduce function to calculate the sum along with a lambda expression:

reduce(lambda x,y:x+y,d.values())
查看更多
做个烂人
3楼-- · 2019-01-10 02:48

Sure there is. Here is a way to sum the values of a dictionary.

>>> d = {'key1':1,'key2':14,'key3':47}
>>> sum(d.values())
62
查看更多
欢心
4楼-- · 2019-01-10 02:49

As you'd expect:

sum(d.values())

In Python<3, you may want to use itervalues instead (which does not build a temporary list).

查看更多
够拽才男人
5楼-- · 2019-01-10 03:02

In Python 2 you can avoid making a temporary copy of all the values by using the itervalues() dictionary method, which returns an iterator of the dictionary's keys:

sum(d.itervalues())

In Python 3 you can just use d.values() because that method was changed to do that (and itervalues() was removed since it was no longer needed).

To make it easier to write version independent code which always iterates over the values of the dictionary's keys, a utility function can be helpful:

import sys

def itervalues(d):
    return iter(getattr(d, ('itervalues', 'values')[sys.version_info[0]>2])())

sum(itervalues(d))

This is essentially what Benjamin Peterson's six module does.

查看更多
唯我独甜
6楼-- · 2019-01-10 03:12
d = {'key1': 1,'key2': 14,'key3': 47}
sum1 = sum(d[item] for item in d)
print(sum1)

you can do it using the for loop

查看更多
登录 后发表回答