I have a python dictionary say
d = {"david":30, "vivian":40, "tom":20,"echo":40}
My goal is
- to return the key with the largest value.
- 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?
>Solution :
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) .