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.
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.
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().
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.
Use the builtin function max . Example: max(2, 4) returns 4.
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])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With