user3275064
user3275064

Reputation: 11

Highest number in dictionary values

How can I retrieve the key in the dictionary which contains the highest number in its list of values?

l = {
 '1': [1, 2, 3, 4, 5, 6, 8, 9, 10, 11], 
 '3': [1, 2, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],
 '5': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 21, 17, 18, 19],
 '4': [4, 1, 2, 3, 5, 6],
 '7': [1, 2, 8, 3, 4, 5, 6, 7]
}

In this example key 5 contains a value 19, so this should be returned

Upvotes: 0

Views: 132

Answers (2)

Jean-François Fabre
Jean-François Fabre

Reputation: 140297

you can apply max on the dictionary keys converted to list (python 3), using a key function which returns the maximum value of the list

l = {'1': [1, 2, 3, 4, 5, 6, 8, 9, 10, 11],
 '3': [1, 2, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],
 '5': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 21, 17, 18, 19],
 '4': [4, 1, 2, 3, 5, 6],
 '7': [1, 2, 8, 3, 4, 5, 6, 7]}

print(max(list(l.keys()),key=lambda k:max(l[k])))

result: 5

EDIT: that works, but unnecessarily queries the dict when computing the maximum. Better get the key+value pairs and work on the list of tuples. In the end, take the first element. Should be slightly faster (no key lookup):

max(list(l.items()),key=lambda v:v[1][-1])[0]

Upvotes: 3

Ajax1234
Ajax1234

Reputation: 71471

You can try this:

l = {
  '1': [1, 2, 3, 4, 5, 6, 8, 9, 10, 11], 
  '3': [1, 2, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],
  '5': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 21, 17, 18, 19],
  '4': [4, 1, 2, 3, 5, 6],
  '7': [1, 2, 8, 3, 4, 5, 6, 7]
}
final_val = sorted(l.items(), key=lambda x: max(x[-1]))[-1][0]
print(final_val)

Output:

5

Upvotes: 0

Related Questions