0

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?

Alec
  • 1,986
  • 4
  • 23
  • 47

2 Answers2

3

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.

user2390182
  • 72,016
  • 6
  • 67
  • 89
1

Maybe

max(counts.values())

would work?


From the Python documentation:

A Counter is a dict 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().

iBug
  • 35,554
  • 7
  • 89
  • 134