Home > Software engineering >  How to find the mean of every element in a python dictionary using for loop
How to find the mean of every element in a python dictionary using for loop

Time:11-17

 comp_dict = {'ap': {'val': 0.3, 'count': 3}, 'sd': {'val': 0.02, 'count': 1}, 'ao': {'val': 0.01, 'count': 1}}

 avg_rate = {}
 for value in comp_dict.keys():
     avg_rate[value] = comp_dict[value]['val']/comp_dict[value]['count']
 print(avg_rate[value])

It seems like the output I got only generates the average I want for the last element and I am wondering how is it possible for me to get the mean for all three elements.

the output i got now is just 0.01

My desired output would be something like {ap:0.1,sd:0.02,ao:0.01}

Thanks a lot!

CodePudding user response:

I guess that would work

avg_rate = {k:comp_dict[k]['val']/comp_dict[k]['count'] for k in comp_dict for k2 in comp_dict[k]}

CodePudding user response:

You just made a little mistake when you print out the avg_rate value.

you can do this:

avg_rate = {}
 for value in comp_dict.keys():
     avg_rate[value] = comp_dict[value]['val']/comp_dict[value]['count']
 print(avg_rate)

given comp_dict = {'ap': {'val': 0.3, 'count': 3}, 'sd': {'val': 0.02, 'count': 1}, 'ao': {'val': 0.01, 'count': 1}} ,

the output is:

{'ap': 0.09999999999999999, 'sd': 0.02, 'ao': 0.01}

  • Related