Reputation: 2154
Scenario
Given a few lines of code, I have included the line
counts = Counter(rank for rank in ranks)
because I want to find the highest count of a character in a string.
So I end up with the following object:
Counter({'A': 4, 'K': 1})
Here, the value I'm looking for is 4
, because it is the highest count. Assume the object is called counts
, then max(counts)
returns 'K'
, presumably because 'K' > 'A'
in unicode.
Question
How can I access the largest count/value, rather than the "largest" key?
Upvotes: 1
Views: 4923
Reputation: 73460
You can use max
as suggested by others. Note, though, that the Counter
class provides the most_common(k)
method which is slightly more flexible:
counts.most_common(1)[0][1]
Its real performance benefits, however, will only be seen if you want more than 1
most common element.
Upvotes: 4
Reputation: 37227
Maybe
max(counts.values())
would work?
From the Python documentation:
A
Counter
is adict
subclass for counting hashable objects. It is a collection where elements are stored as dictionary keys and their counts are stored as dictionary values.
So you should treat the counter as a dictionary. To take the biggest value, use max()
on the counters .value()
.
Upvotes: 1