Python dict中的所有值的总和 [英] Sum of all values in a Python dict

查看:475
本文介绍了Python dict中的所有值的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很习惯Python。假设我有一个字典,其中的键映射为整数,如:

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

是否有一种语法上简约的方式来返回d - ie中的值



谢谢

解决方案

期望:

  sum(d.values())

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


I'm new to Python. 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.

Thanks

解决方案

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 dict中的所有值的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆