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

后端 未结 3 480
余生分开走
余生分开走 2021-01-28 17:17

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

3条回答
  •  旧巷少年郎
    2021-01-28 17:42

    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.

提交回复
热议问题