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

前端 未结 10 1351
挽巷
挽巷 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:51

    Iteration over a dictionary iterates over its keys. Try just using for key in G, and then using G[key] appropriately instead of values.

    Alternatively, use the iteritems() method of the dictionary to get key, value pairs from G, i.e.:

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

    (For the record, your actual method of computing a mean doesn't look right to me, but you may as well fix the iteration problem first).

提交回复
热议问题