Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

return key according to value of python dictionary

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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) .

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading