Stagg Stagg - 7 months ago 17
Python Question

Average of key values in a list of dictionaries

I have this list of dictionaries :

[{'Eva': [4, 8, 2]}, {'Ana': [57, 45, 57]}, {'Ada': [12]}]


I need to get the average of each key value, so that the output is :

[{'Eva': [5], {'Ana' : [53]}, {'Ada':[12]}]


The average must be rounded up or down by adding 0.5 and taking the only the integer part. For example, if the average is 4.3 adding 0.5 equals 4.8, so the output is 4. If the average is 4.6 adding 0.5 equals 5.1, so the output is 5.

I know how to use
iteritems()
to iterate over a dictionary, but since this is a list I don't know how to reach every value.

Thanks in advance.

Answer

You can use zip and numpy functions mean and round for this task:

In [8]: import numpy as np

In [9]:  [dict(zip(d.keys(), [int(np.round(np.mean(d.values())))])) for d in L]

#Out[9]: [{'Eva': 5}, {'Ana': 53}, {'Ada': 12}]

Version with "less" parenthesis:

[dict(zip(d.keys(), [np.array(d.values()).mean().round().astype(int)])) for d in L]