Home > database >  return key according to value of python dictionary
return key according to value of python dictionary

Time:02-18

I have a python dictionary say

d = {"david":30, "vivian":40, "tom":20,"echo":40}

My goal is

  1. to return the key with the largest value.
  2. In case there is a tie in the value, the key with the shortest length (number of letters) will be prioritized. So in this case, "echo" will be returned.

I can achieve first goal with

max_key = max(d, key=d.get)

How can I achieve the second goal?

CodePudding user response:

max() orders the items by the value returned by the key argument, so the key here is to figure out a way to order the shorter dictionary keys first. You can do this by returning a tuple from the key function, which contains the value and the length of the dictionary key.

max_key = max(d, key=lambda k: (d[k], -len(k)))
# 'echo'

Since you're using the max function and you want the smallest length selected, you have to use -len(k) .

CodePudding user response:

There may be a more concise way to do this but this seems to work:

d = {"david":30, "vivian":40, "tom":20,"echo":40}

print(sorted([(v, k) for k, v in d.items()], key=lambda x: (x[0], -len(x[1])))[-1])

Output:

(40, 'echo')
  • Related