0

I am trying to return the variable having the maximum value. But if the variable have the common values than the max() is returning only one value. Her eis the what I got:

>>> d = {'x1':2,'x2':2}
>>> max(d, key=d.get)
'x2'

As one can see the values of both variables is 2, the max() is returning the the output as one variable only and not both the larger values.

Kindly, let me know how max() can return multiple maximum values?

Jaffer Wilson
  • 7,029
  • 10
  • 62
  • 139
  • `max` can't return multiple values. If you want a function that does that, you'll have to write it yourself. – Barmar Sep 16 '17 at 06:33

1 Answers1

0

There’s nothing built in for this, but you can use the same strategy that max does:

def max_all(iterable, *, key):
    it = iter(iterable)
    max_values = [next(it)]
    max_key = key(max_values[0])

    for x in it:
        x_key = key(x)

        if x_key > max_key:
            max_values = [x]
            max_key = x_key
        elif x_key == max_key:
            max_values.append(x)

    return max_values

demo

Ry-
  • 218,210
  • 55
  • 464
  • 476