Python dict中的所有值的总和(How to sum all the values in a dictionary?)
我是Python的新手 假设我有一个字典,其中键映射为整数,如:
d = {'key1':1,'key2':14,'key3':47}在这种情况下,是否有一种语法上简单的方法来返回d - 即62中的值的总和。
谢谢
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?
最满意答案
正如你所料:
sum(d.values())在Python <3中,您可能需要使用itervalues (不构建临时列表)。
As you'd expect:
sum(d.values())In Python<3, you may want to use itervalues instead (which does not build a temporary list).
更多推荐
发布评论