Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Python's max to return two equally large values

I'm using Python's max function to find the largest integer in a dictionary called count, and the corresponding key (not quite sure if I'm saying it properly; my code probably explains itself better than I'm explaining it). The dictionary count is along the lines of {'a': 100, 'b': 210}, and so on.

number = count[max(count.items(), key=operator.itemgetter(1))[0]]
highest = max(count, key=count.get)

What would I do if there were two equal largest values in there? If I had {'a': 120, 'b': 120, 'c': 100}, this would only find the first of a and b, not both.

like image 983
kidosu Avatar asked Mar 24 '12 16:03

kidosu


People also ask

Can Max return two values Python?

Passing Two or More Values to the Python max() MethodWhen two or more values are passed to the max() method, it returns the maximum or largest of them all. These arguments can be integers, floating-point values, characters or even strings.

What does Max function return if both values are equal?

It compares the two numbers passed in its arguments and returns the larger of the two, and if both are equal, then it returns the first one. It can also compare the two numbers using a binary function, which is pre-defined by the user, and then passed as argument in std::max().

How does Max () work in Python?

Python max() Function The max() function returns the item with the highest value, or the item with the highest value in an iterable. If the values are strings, an alphabetically comparison is done.

How do you choose greater of two values in Python?

Use the builtin function max . Example: max(2, 4) returns 4.


1 Answers

Idea is to find max value and get all keys corresponding to that value:

count = {'a': 120, 'b': 120, 'c': 100}

highest = max(count.values())

print([k for k, v in count.items() if v == highest])
like image 66
Asterisk Avatar answered Sep 18 '22 17:09

Asterisk