find the average of all values in a map in python

Here's an example of how you could find the average of all values in a Python dictionary (which is similar to a map in other languages) using the built-in mean function from the statistics module:

main.py
import statistics

# Example dictionary
my_dict = {'a': 1, 'b': 2, 'c': 3, 'd': 4}

# Get a list of all values in the dictionary
values_list = list(my_dict.values())

# Calculate the mean of the values using statistics.mean()
average = statistics.mean(values_list)

print("The average of all values in the dictionary is:", average)
332 chars
13 lines

Output:

main.py
The average of all values in the dictionary is: 2.5
52 chars
2 lines

Alternatively, you could calculate the average manually using a loop:

main.py
# Example dictionary
my_dict = {'a': 1, 'b': 2, 'c': 3, 'd': 4}

# Calculate the sum of all values in the dictionary
sum_of_values = 0
for value in my_dict.values():
    sum_of_values += value

# Calculate the average of the values
average = sum_of_values / len(my_dict)

print("The average of all values in the dictionary is:", average)
338 chars
13 lines

Output:

main.py
The average of all values in the dictionary is: 2.5
52 chars
2 lines

gistlibby LogSnag