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

sort list based on dictionary values even with missing keys

I am trying to sort a list based on dictionary values. The only problem is that if a list contains something that doesn’t exist in the dictionary it wont sort it.

here is what I have

d = {
    "hello0" : 0,
    "hello1" : 1,
    "hello2" : 2,
    "hello3" : 3
          
}


l1 = ["hello1","hello3","hello0","hello2"] #list 1
l2 = ["hello4","hello1","hello3","hello0","hello2"] #list 2



try:
    sorted_l1 = sorted(l1,key=lambda x : d[x])
    sorted_l2 = sorted(l2,key=lambda x : d[x])
    #print(sorted_l1)
    print(sorted_l2)
except Exception as e:      
    print(f"Keyerror {e}")

List 1 will get sorted just fine because everything in that list exists in the dictionary but list 2 will not get sorted and will get a keyerror.

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

How do I sort list 2 so that the missing key gets added to the end of the sorted list 2 ?
Do I use {}.get ? or is there some another way ?

>Solution :

max_value_dict = max(d.values())
sorted_l2 = sorted(l2,key=lambda x : d.get(x, max_value_dict + 1))

Whenever x is not a key in d, the value associated to x by d.get in the sort is strictly greater than every value in d. Thus x is placed at the end.

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