Finding mean of a values in a dictionary without using .values() etc

前端 未结 10 1354
挽巷
挽巷 2021-01-02 17:29

I have a dictionary that looks like:

G={\'E\': 18.0, \'D\': 17.0, \'C\': 19.0, \'B\': 15.0, \'A\': 0}

I have to find the mean of the values

10条回答
  •  天涯浪人
    2021-01-02 17:55

    Use G.values() to get all the values from a dictionary.

    G = {'E': 18.0, 'D': 17.0, 'C': 19.0, 'B': 15.0, 'A': 0}
    d = float(sum(G.values())) / len(G)
    print (d)
    

    This prints 13.8.

    Note that there is a difference between Python 2 and Python 3 here. In Python 2, G.values() is a newly constructed list of values. In Python 3, it is a generator, which can be thought of as a “lazy list”. The same thing is called G.itervalues() in Python 2.

提交回复
热议问题