从键转换字典:值到值:出现次数

时间:2013-08-04 16:27:52

标签: python dictionary

假设我有一本字典如下

d = {1: 7, 2: 8, 3: 9, 4: 7, 5: 8, 6: 9, 7: 7, 8: 8, 9: 9, 10: 9}

如何获取按降序排序的最常见值的字典?

所以我希望

res = {9: 4, 8: 3, 7: 3}

1 个答案:

答案 0 :(得分:6)

使用collections.Counter

>>> from collections import Counter
>>> d = {1: 7, 2: 8, 3: 9, 4: 7, 5: 8, 6: 9, 7: 7, 8: 8, 9: 9, 10: 9}
>>> Counter(d.values())
Counter({9: 4, 8: 3, 7: 3})
>>> Counter(d.values()).most_common()
[(9, 4), (8, 3), (7, 3)]