How to find the 2nd max of a Counter - Python

alvas picture alvas · Apr 6, 2013 · Viewed 13.2k times · Source

The max of a counter can be accessed as such:

c = Counter()
c['foo'] = 124123
c['bar'] = 43
c['foofro'] =5676
c['barbar'] = 234
# This only prints the max key
print max(c), src_sense[max(c)] 
# print the max key of the value
x = max(src_sense.iteritems(), key=operator.itemgetter(1))[0]
print x, src_sense[x]

What if i want a sorted counter in descending counts?

How do i access the 2nd maximum, or the 3rd or the Nth maximum key?

Answer

DSM picture DSM · Apr 6, 2013

most_common(self, n=None) method of collections.Counter instance

List the n most common elements and their counts from the most common to the least. If n is None, then list all element counts.

>>> Counter('abcdeabcdabcaba').most_common(3)
[('a', 5), ('b', 4), ('c', 3)]

and so:

>>> c.most_common()
[('foo', 124123), ('foofro', 5676), ('barbar', 234), ('bar', 43)]
>>> c.most_common(2)[-1]
('foofro', 5676)

Note that max(c) probably doesn't return what you want: iteration over a Counter is iteration over the keys, and so max(c) == max(c.keys()) == 'foofro', because it's the last after string sorting. You'd need to do something like

>>> max(c, key=c.get)
'foo'

to get the (a) key with the largest value. In a similar fashion, you could forego most_common entirely and do the sort yourself:

>>> sorted(c, key=c.get)[-2]
'foofro'