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