深度阅读

How to get the sum of the values in a Python dictionary?

作者
作者
2023年08月22日
更新时间
6.61 分钟
阅读时间
0
阅读量

To get the sum of the values in a Python dictionary, you can use the built-in sum() function. Here’s an example:

my_dict = {'key1': 10, 'key2': 45, 'key3': 23}
sum_values = sum(my_dict.values())
print(sum_values)  # Output: 78

In this example, sum() is called with my_dict.values() as an argument, which returns a view object of the dictionary’s values. The resulting sum of values is stored in the sum_values variable and printed to the console.

Note that this method assumes that the values in the dictionary are numeric types that can be added together. If not, you may get a TypeError when trying to add non-numeric types together.

相关标签

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。