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

average, dictionary, python

Solution

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

Problem

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] ``` and so forth. In total I have 48 different keys. What I am trying to get is the average of the three numbers. So I would get a dict that looks like this . . . ``` AvgDictName = {'Abamectin': [49], 'Difenzoquat metilsulfate': [128], 'Chlorpyrifos': [32], 'Dibutyl phthalate': [-3] . . . ``` I have tried using this line ``` AvgDictName = dict([(key, float(sum([int(i) for i in values])) / len(values)) for key, values in CombinedDict]) ``` But I am getting too many values to unpack error Any ideas? I think it could also be done by making the dict into a list and finding the average from a list using len and sum commands and then converting back to a dict but I do not really know how to go about that. Thank you, I have a feeling this should easy.

Original source