Python How to find the average of multiple values ​​/ key in a dictionary

I have a dictionary that looks like this.,

CombinedDict = {'Abamectin': [63, 31, 53], 'Difenzoquat metilsulfate': [185, 49, 152], 'Chlorpyrifos': [14, 26, 56], 'Dibutyl phthalate': [25, -17, -18] 

etc. In total, I have 48 different keys.

What I'm trying to get is the average of three numbers. So I would get a voice recorder that looks like this.,

  AvgDictName = {'Abamectin': [49], 'Difenzoquat metilsulfate': [128], 'Chlorpyrifos': [32], 'Dibutyl phthalate': [-3] . . . 

I tried to use this line

  AvgDictName = dict([(key, float(sum([int(i) for i in values])) / len(values)) for key, values in CombinedDict]) 

But I get too many values ​​to unpack the error Any ideas? I think this could also be done by entering a dict into the list and finding the middle of the list using the len and sum commands, and then returning to the dict, but I really don't know how to do this. Thank you, I have the feeling that it is easy.

+6
source share
3 answers

You need to CombinedDict.items() over CombinedDict.items() or CombinedDict.iteritems() if you want to unpack in key, values

+5
source

for x in dictionary: ... iterates over the keys of the dictionary.

If the keys themselves are not tuples, for a, b in dictionary will be an error, as it tries to unpack the key into two values.

To iterate over dictionaries you should use items() , keys() and values() (or their equivalents iter* in python 2.x)

0
source
  python 3.2 >>> [(i,sum(v)//len(v)) for i,v in t.items()] 
0
source

All Articles