Eri*_*aus 4 python dictionary list python-3.x
我有这个 dictionary (key,list)
index={'chair':['one','two','two','two'],'table':['two','three','three']}
Run Code Online (Sandbox Code Playgroud)
我想要这个
#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}}
Run Code Online (Sandbox Code Playgroud)
我想我应该使用lambda表达式,但不知道我怎么能这样做.有帮助吗?
首先,将您的值正确定义为列表:
index = {'chair': ['one','two','two','two'], 'table': ['two','three','three']}
Run Code Online (Sandbox Code Playgroud)
然后使用collections.Counter字典理解:
from collections import Counter
Run Code Online (Sandbox Code Playgroud)
- 每个键中出现每个值的次数.
res1 = {k: Counter(v) for k, v in index.items()}
Run Code Online (Sandbox Code Playgroud)
- 每个键的最大金额值
res2 = {k: v.most_common()[0][1] for k, v in res1.items()}
Run Code Online (Sandbox Code Playgroud)
- 我们将#1中的每个值除以#2中的值
res3 = {k: {m: n / res2[k] for m, n in v.items()} for k, v in res1.items()}
Run Code Online (Sandbox Code Playgroud)