1

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?

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

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().

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.