Average value in multiple dictionaries based on key in Python?

无人久伴 提交于 2020-12-08 08:03:31

问题


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}

回答1:


You can use Pandas, like this:

import pandas as pd
df = pd.DataFrame([A,B,C])
answer = dict(df.mean())
print(answer)



回答2:


I use Counter to solve this problem. Please try the following code :)

from collections import Counter

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}

sums = Counter()
counters = Counter()
for itemset in [A, B, C]:
    sums.update(itemset)
    counters.update(itemset.keys())

ret = {x: float(sums[x])/counters[x] for x in sums.keys()}

print ret



回答3:


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}



回答4:


If you are working in python 2.7 or 3.5 you can use the following:

keys = set(A.keys()+B.keys()+C.keys())

D = {key:(A.get(key,0)+B.get(key,0)+C.get(key,0))/float((key in A)+(key in B)+(key in C)) for key in keys}

which outputs

 D
{'a': 1.0, 'c': 2.0, 'b': 1.5, 'e': 4.0, 'd': 3.0, 'g': 5.0, 'f': 4.5}

if you don't want to use any packages. This doesn't work in python 2.6 and below though.



来源:https://stackoverflow.com/questions/34139512/average-value-in-multiple-dictionaries-based-on-key-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!