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.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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])

Method 2

Same idea as Asterisk, but without iterating over the list twice. Bit more verbose.

count = { 'a': 120, 'b': 120, 'c': 100 }
answers = []
highest = -1

def f(x):
    global highest, answers
    if count[x] > highest:
        highest = count[x]
        answers = [x]
    elif count[x] == highest:
        answers.append(x)

map(f, count.keys())
print answers

Method 3

Fast single pass:

a = { 'a': 120, 'b': 120, 'c': 100 }
z = [0]
while a:
    key, value = a.popitem()
    if value > z[0]:
        z = [value,[key]]
    elif value == z[0]:
        z[1].append(key)

print z
#output:
[120, ['a', 'b']]

And an amusing way with defaultdict:

import collections
b = collections.defaultdict(list)
for key, value in a.iteritems():
    b[value].append(key)
print max(b.items())
#output:
(120, ['a', 'b'])

Method 4

This could be a way (probably not the most efficient).

value = max(count.values())
filter(lambda key: count[key]==value,count)

Method 5

Sometimes simplest solution may be the best:

max_value = 0
max_keys = []

for k, v in count.items():
    if v >= max_value:
        if v > max_value:
            max_value = v
            max_keys = [k]
        else:
            max_keys.append(k)

print max_keys

The code above is slightly faster than two pass solution like:

highest = max(count.values())
print [k for k,v in count.items() if v == highest]

Of course it’s longer, but on the other hand it’s very clear and easy to read.

Method 6

To print a list without bucket. use :

' '.join(map(str, mylist))

or, more verbosely:

' '.join(str(x) for x in mylist)


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x