如何总结字典中的所有值? [英] How to sum all the values in a dictionary?

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

问题描述

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

是否有句法简约的方式返回 d -ie中的值的总和 62 在这种情况下?

解决方案

/ p>

  sum(d.values())

在Python< 3中,您可能希望使用 itervalues (而不是构建临时列表)。

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?

解决方案

As you'd expect:

sum(d.values())

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

这篇关于如何总结字典中的所有值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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