1

I have the following script:

data = [['A', 4], ['B', 12], 
        ['C', 20], ['D', 38], 
        ['E', 88], ['F', 88]]
        
print(max(data, key=lambda x: x[1]))

I get as an output only ['E', 88]. How could I get ['E', 88], ['F', 88] because both have the same highest value?

user977828
  • 7,259
  • 16
  • 66
  • 117
  • 2
    `mx = max(data, key=lambda x: x[1])[1]; mx_values = [[l, v] for l, v in data if v == mx]; print(mx_values) # [['E', 88], ['F', 88]]` – azro Nov 12 '20 at 21:45
  • 1
    @azro `max_values = [couple for couple in data if couple[1] == mx]` so that the result is always in the same container as the base data without having to specify that it's a list (your `[l, v]`). – Guimoute Nov 12 '20 at 21:47
  • @Guimoute Is azro's solution wrong? – user977828 Nov 12 '20 at 22:35
  • @user977828 No it works, but if you change your `data` to contain tuples (`data = [('A', 4), (B', 12), ...]`) the value returned by azro's method will be lists instead of tuples. – Guimoute Nov 13 '20 at 09:33

1 Answers1

2

You could do:

data = [['A', 4], ['B', 12],
        ['C', 20], ['D', 38],
        ['E', 88], ['F', 88]]

lookup = {}

for pair in data:
    lookup.setdefault(pair[1], []).append(pair)


max_key = max(lookup)

print(lookup[max_key])

Output

[['E', 88], ['F', 88]]

The function setdefault, does the following (from the documentation):

If key is in the dictionary, return its value. If not, insert key with a value of default and return default. default defaults to None.

Dani Mesejo
  • 61,499
  • 6
  • 49
  • 76