Reputation: 3233
I have a list of dictionary like this
data = [{'Name': 'john', 'Height': 176, 'Weight':62, 'IQ':120,..},...]
the .. signifies various other integer/float attributes and all elements of the list has same format..
I want to get the average Height, Weight and all other numerical attributes in the cleanest/easiest way.
I could not come up with a better way than normal for looping which was too messy... and i don't want to use any external packages
Upvotes: 0
Views: 1168
Reputation: 2786
You can use the following
sum([item['Weight'] for item in data])/len(data)
and use
float(len(data))
if you want a more exact value.
Upvotes: 1
Reputation: 52071
Here is a start for you
>>> data = [{'Name': 'john', 'Height': 176},{'Name': 'Vikash', 'Height': 170}]
>>> vals = [i['Height'] for i in data]
>>> sum(vals)/len(vals)
173
Likewise you can have a different loop for each attribute or put the loop in a function
>>> def avrg(data,s):
... vals = [i[s] for i in data]
... return sum(vals)/len(vals)
...
>>> data = [{'Name': 'john', 'Height': 176, 'Weight':62, 'IQ':120,},{'Name': 'Vikash', 'Height': 170, 'Weight':68, 'IQ':100}]
>>>
>>> avrg(data,'Weight')
65
Upvotes: 1
Reputation: 4964
Yeah there really isn't a better way than looping. Your basic issue is you have to look at each element in the list, you can't really do that without looping.
Upvotes: 1