I have a dictionary:
my_dict = {'A': [-1,-1,-1], 'B': [-1,-1,-1], 'C': [0,0,1]}
my_list=['A','C']
I want to find the average for 'A' and 'C' such that the average is a new list that contains the values for the dictionary keys A and C divided by 2:
result=[(-1+0)/2, (-1+0)/2, (-1+1)/2]
i.e, result=[-0.5, -0.5, 0.0]
How can I compute the result ? Note that my_list=['A','C']
is not fixed, so please do not use fixed values.
EDIT: my_list=['A','C']
is a variable passed to a function. It could be for example ['A','B','C']. So please, consider this. I can not use 'A' and 'C' explicitly in the code.
Sounds like you really want to be using pandas, or at least numpy. In pandas this is:
import pandas as pd
data = pd.DataFrame({'A': [-1,-1,-1], 'B': [-1,-1,-1], 'C': [0,0,1]})
my_list = ['A', 'C']
data[my_list].mean(axis=1)
In any case, in normal python this is:
[sum(values)/float(len(my_list)) for values in zip(*[my_dict[key] for key in my_list])]
from __future__ import division # for python < 3 only
my_dict = {'A': [-1,-1,-1], 'B': [-1,-1,-1], 'C': [0,0,1]}
my_list=['A','C']
l = []
for v in zip(*(my_dict[x] for x in my_list)):
l += [ sum(v) / len(v) ]
If you have Python 2.x then you need the future.division for float division. The above should work for any number of items in my_list
. For example, for my_list = ['A,' B', 'C']
, it yields:
[-0.666, -0.666, -0.333]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With