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????
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.
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.
import numpy as np
np.mean(list(dict.values()))
If you use numpy:
import numpy as np
np.array(list(dict.values())).mean()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With