Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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 e.g. mean(18,17,19,15,0) using a simple for loop without using built in functions like .values(), .items() and so on. I tried the following but am getting an error:

d=[float(sum(values)) / len(values) for key, values in G]
    return (d)   
ValueError: need more than 1 value to unpack

Can someone help me fix this????

like image 223
Rachel Avatar asked Mar 14 '14 21:03

Rachel


People also ask

How do you find the average value of a dictionary?

You can do this by iterating over the dictionary and filtering out zero values first. Then take the sum of the filtered values. Finally, divide by the number of these filtered values.

How do you find the sum of a value in a dictionary?

It is pretty easy to get the sum of values of a python dictionary. You can first get the values in a list using the dict. values(). Then you can call the sum method to get the sum of these values.


2 Answers

import numpy as np
np.mean(list(dict.values()))
like image 151
insanely_sin Avatar answered Sep 22 '22 17:09

insanely_sin


If you use numpy:

import numpy as np

np.array(list(dict.values())).mean()
like image 29
Sergio R Avatar answered Sep 20 '22 17:09

Sergio R