Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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] 

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.

like image 986
user1871086 Avatar asked Dec 02 '12 22:12

user1871086


People also ask

Can a Python dictionary have multiple values per key?

In python, if we want a dictionary in which one key has multiple values, then we need to associate an object with each key as value. This value object should be capable of having various values inside it. We can either use a tuple or a list as a value in the dictionary to associate multiple values with a key.

How do you average a dictionary?

Solution: Use the sum() and len() function Use the sum(dictionary. values()) function to calculate the sum of values in a dictionary. ​Use len(dictionary) to calculate the length of dictionary, then divide the sum by length to calculate the average.

How do you check if multiple keys are in a dictionary python?

isSubset() to check multiple keys exist in Dictionary The python isSubset() method returns true if all the elements of the set passed as argument present in another subset else return false.


1 Answers

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

like image 134
Jesse the Game Avatar answered Sep 22 '22 07:09

Jesse the Game