How can I calculate average of different values in each key of python dictionary?

橙三吉。 提交于 2020-11-29 21:04:37

问题


I have a dictionary. I want to calculate average of values for each key and print result so that the result shows key and associated average. The following code calculates mean but I don't know how to associate key with the average. My desired answer is Mean = {22:average1, 23:average2, 24:average3}.

          mydict = {22: [1, 0, 0, 1], 23: [0, 1, 2, 1, 0], 24: [3, 3, 2, 1, 0]}

          Mean =[float(sum(values)) / len(values) for key, values in 
          mydict.iteritems()]

回答1:


Don't use a list comprehension. Use a dictionary comprehension to calculate the average of each list. You can also from __future__ import division to avoid having to use float:

>>> from __future__ import division
>>> d = {22: [1, 0, 0, 1], 23: [0, 1, 2, 1, 0], 24: [3, 3, 2, 1, 0]}
>>> mean = {k: sum(v) / len(v) for k, v in d.iteritems()}
>>> mean
{22: 0.5, 23: 0.8, 24: 1.8}



回答2:


You were on the right track. You just needed a dictionary comprehension instead of a list comp.

_dict = {22: [1, 0, 0, 1], 23: [0, 1, 2, 1, 0], 24: [3, 3, 2, 1, 0]}

mean = {key : float(sum(values)) / len(values) for key, values in _dict.iteritems()}
print(mean) 
{22: 0.5, 23: 0.8, 24: 1.8}

Notes:

  1. .iteritems is replaced with .items in python3
  2. (Statutory Warning) Do not use dict as a variable name, it shadows the builtin class with the same name.



回答3:


Update for Python 3.4+

>>> from statistics import mean    # Python 3.4+
>>> d = {22: [1, 0, 0, 1], 23: [0, 1, 2, 1, 0], 24: [3, 3, 2, 1, 0]}
>>> {k:mean(v) for k,v in d.items()}
{22: 0.5, 23: 0.8, 24: 1.8}
>>>


来源:https://stackoverflow.com/questions/46082236/how-can-i-calculate-average-of-different-values-in-each-key-of-python-dictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!