python - 计算不同的字典值

标签 python python-3.x list dictionary

我有这个字典(键,列表)

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
  1. number of times each value occurs in each key.
res1 = {k: Counter(v) for k, v in index.items()}
  1. value for maximum amount for each key
res2 = {k: v.most_common()[0][1] for k, v in res1.items()}
  1. 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/

相关文章:

python - 捕获程序调试事件消息

python - Django,在提交表单时从另一个 View 返回一个 View

list - 笛卡尔积类型错误

python - 如何从单个词典创建词典列表?

C++ 列表插入奇怪的行为

python - 使用 pygame 通过按键结束循环

python - Unicode编码错误: 'charmap' codec can't encode character '\U0001f937' in position 0: character maps to <undefined>

python - 计算二叉树中每个级别的节点数

python - 将列表中的空值替换为另一个列表中的值

python - Python 中的命令输出解析