Getting the most common value-s collections.Counter.most common

suggest change

Counting the keys of a Mapping isn’t possible with collections.Counter but we can count the values:

from collections import Counter
adict = {'a': 5, 'b': 3, 'c': 5, 'd': 2, 'e':2, 'q': 5}
Counter(adict.values())
# Out: Counter({2: 2, 3: 1, 5: 3})

The most common elements are avaiable by 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)]

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents