Python dict中的所有值的总和(How to sum all the values in a dictionary?)

编程入门 行业动态 更新时间:2024-10-25 00:29:58
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).

更多推荐

本文发布于:2023-08-02 20:09:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1379543.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:总和   dict   Python   dictionary   values

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!