深度阅读

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

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

To get the average of the values in a Python dictionary, you can use the mean() function from the statistics module. Here’s an example:

import statistics

my_dict = {'key1': 10, 'key2': 45, 'key3': 23}
avg_value = statistics.mean(my_dict.values())
print(avg_value)  # Output: 26.0

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

Note that this method requires Python 3.x and assumes that the values in the dictionary are numeric types that can be averaged together. If not, you may get a TypeError when trying to average non-numeric types together.

相关标签

博客作者

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