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

Published on Aug. 22, 2023, 12:17 p.m.

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.

Tags: