Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Average value in multiple dictionaries based on key in Python?

I have three dictionaries (or more):

A = {'a':1,'b':2,'c':3,'d':4,'e':5}
B = {'b':1,'c':2,'d':3,'e':4,'f':5}
C = {'c':1,'d':2,'e':3,'f':4,'g':5}

How can I get a dictionary of the average values of every key in the three dictionaries?

For example, given the above dictionaries, the output would be:

{'a':1/1, 'b':(2+1)/2, 'c':(3+2+1)/3, 'd':(4+3+2)/3, 'e':(5+4+3)/3, 'f':(5+4)/2, 'g':5/1}
like image 380
HAO CHEN Avatar asked Dec 07 '15 17:12

HAO CHEN


2 Answers

The easiest way would be to use collections.Counter as explained here, like this:

from collections import Counter

sums = dict(Counter(A) + Counter(B) + Counter(C))
# Which is {'a': 1, 'c': 6, 'b': 3, 'e': 12, 'd': 9, 'g': 5, 'f': 9}

means = {k: sums[k] / float((k in A) + (k in B) + (k in C)) for k in sums}

The result would be:

>>> means
{'a': 1.0, 'b': 1.5, 'c': 2.0, 'd': 3.0, 'e': 4.0, 'f': 4.5, 'g': 5.0}
like image 152
Marco Bonelli Avatar answered Oct 17 '22 06:10

Marco Bonelli


You can use Pandas, like this:

import pandas as pd
df = pd.DataFrame([A,B,C])
answer = dict(df.mean())
print(answer)
like image 24
Maxim Imakaev Avatar answered Oct 17 '22 07:10

Maxim Imakaev