-1

How can you average the value in a dictionary if it's a list? What follows is the code I have with the correct answer. I cannot use slicing techniques

dict = {'zy': [1.0, 0.9, 0.8, 0.7]}
# code to average the values
print(dict)
{'zy': 0.85}
Pranav Hosangadi
  • 23,755
  • 7
  • 44
  • 70
  • You find the mean of a list in a dictionary the exact same way you do for _any list_. The only thing that changes is _how you access that list_. In one case, you do it directly through its variable name. In the other, you do it the _exact same way_ you access _any value inside a dictionary_. Does this answer your question: [Finding the average of a list](https://stackoverflow.com/questions/9039961/finding-the-average-of-a-list) – Pranav Hosangadi Mar 29 '22 at 01:07
  • Does this answer your question? [Finding the average of a list](https://stackoverflow.com/questions/9039961/finding-the-average-of-a-list) – Rayan Hatout Mar 29 '22 at 01:14

1 Answers1

2

Just use simple maths:

dict['zy'] = sum(dict['zy']) / len(dict['zy'])

If you don't want to implement yourself you can use the statistics.mean function:

from statistics import mean
...
dict['zy'] = mean(dict['zy'])

As a side note, don't use built-ins such as dict to name your variables. You will shadow the built-in.

Selcuk
  • 57,004
  • 12
  • 102
  • 110