0

假设我有一本字典如下

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}
4

1 回答 1

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)]
于 2013-08-04T16:28:59.510 回答