我有这个字典(键,列表)
index={'chair':['one','two','two','two'],'table':['two','three','three']}
我想要这个
#1. number of times each value occurs in each key. ordered descending
indexCalc={'chair':{'two':3,'one':1}, 'table':{'three':2,'two':1}}
#2. value for maximum amount for each key
indexMax={'chair':3,'table':2}
#3. we divide each value in #1 by value in #2
indexCalcMax={'chair':{'two':3/3,'one':1/3}, 'table':{'three':2/2,'two':1/2}}
我想我应该使用 lambda 表达式,但想不出我该怎么做。有帮助吗?
最佳答案
首先,将您的值正确定义为列表:
index = {'chair': ['one','two','two','two'], 'table': ['two','three','three']}
然后使用带有字典理解的collections.Counter
:
from collections import Counter
- number of times each value occurs in each key.
res1 = {k: Counter(v) for k, v in index.items()}
- value for maximum amount for each key
res2 = {k: v.most_common()[0][1] for k, v in res1.items()}
- we divide each value in #1 by value in #2
res3 = {k: {m: n / res2[k] for m, n in v.items()} for k, v in res1.items()}
关于python - 计算不同的字典值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52469543/