Python:计算字典的重复值

标签 python dictionary count repeat

我有一个字典如下:

dictA = { ('unit1','test1') : 'alpha' , ('unit1','test2') : 'beta', ('unit2','test1') : 'alpha', ('unit2','test2') : 'gamma' , ('unit3','test1') : 'delta' , ('unit3','test2') : 'gamma'   }

如何独立于单位计算每个测试的重复值数量?

在 'test1' 中有 2x 'alpha', 1x 'delta'

在 'test2' 中有 1x 'beta', 2x 'gamma'

有什么意见吗?

非常感谢。

最佳答案

在 Python 2.7 或 3.1 或更高版本中,您可以使用 collections.Counter:

from collections import Counter
counts = Counter((k[1], v) for k, v in dictA.iteritems())
print(counts)

打印

Counter({('test1', 'alpha'): 2, ('test2', 'gamma'): 2, ('test2', 'beta'): 1, ('test1', 'delta'): 1})

关于Python:计算字典的重复值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5490078/

相关文章:

python - 有没有更简单的方法来编写涉及多个组合框和嵌套字典的代码,并且还可以避免 KeyError?

mysql - 按年,月和2个日期字段条件分组

java - 实体集扩展python

ios - 从使用 Mirror 创建的字典中过滤 nil 值

swift - 转换一个快速字典([String :AnyObject] ) to a UnsafeMutablePointer

java - 无限 while 循环以及读取文件时出现问题

php - MySql - 从开始计数到每一天

python - 在 Pandas 系列上链接字符串操作

python - 我可以使用 typing 模块在 python 中为类型构造函数创建类型别名吗?

python - 解析python代码进行静态分析