如何将字典中的所有值相加?

时间:2021-12-17 12:03:37

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?

是否有一种语法上最小的方法来返回d中值的和,即。62在这种情况下吗?

3 个解决方案

#1


274  

As you'd expect:

如您所料:

sum(d.values())

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

在Python<3中,您可能需要使用itervalues(它不构建临时列表)。

#2


59  

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:

在Python 2中,可以通过使用itervalues()字典方法来避免创建所有值的临时副本,该方法返回字典的键的迭代器:

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).

在Python 3中,您可以只使用d.values(),因为该方法被更改为d.values(而itervalues()被删除,因为不再需要它)。

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.

这基本上就是Benjamin Peterson的六个模块所做的。

#3


11  

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

#1


274  

As you'd expect:

如您所料:

sum(d.values())

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

在Python<3中,您可能需要使用itervalues(它不构建临时列表)。

#2


59  

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:

在Python 2中,可以通过使用itervalues()字典方法来避免创建所有值的临时副本,该方法返回字典的键的迭代器:

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).

在Python 3中,您可以只使用d.values(),因为该方法被更改为d.values(而itervalues()被删除,因为不再需要它)。

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.

这基本上就是Benjamin Peterson的六个模块所做的。

#3


11  

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