Getting the most common values collections.Counter.most common
suggest changeA mapping passed to Counter is treated as existing counts, so pass the values to count them:
from collections import Counter
adict = {'a': 5, 'b': 3, 'c': 5, 'd': 2, 'e':2, 'q': 5}
Counter(adict.values())
# Out: Counter({5: 3, 2: 2, 3: 1})
The repr lists elements from most common to least common. Iteration still follows first-seen order: 5, then 3, then 2.
The most common elements are available from the most_common method:
# Sorting them from most-common to least-common value:
Counter(adict.values()).most_common()
# Out: [(5, 3), (2, 2), (3, 1)]
# Getting the most common value
Counter(adict.values()).most_common(1)
# Out: [(5, 3)]
# Getting the two most common values
Counter(adict.values()).most_common(2)
# Out: [(5, 3), (2, 2)]
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents