Sort list by dictionary in Python

Question:

I want to sort a list by a dictionary, as shown below:

The list:

L = ['Jack', 'King', '9', 'King', '10']

The dictionary:

D = {0:'Ace', 1:'King', 2:'Queen', 3:'Jack', 4:'10', 5:'9'}

I want to sort L based on keys of dictionary D, such that the output would be:

[ 'King', 'King', 'Jack', '10', '9' ]

I tried:

sorted(L, key = D.get)

but got error:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
 in 

----> 3 sorted(L, key = D.get)

TypeError: '<' not supported between instances of 'NoneType' and 'NoneType'

Why did I get this error? Aren’t the dictionary keys integers?


Update:

Similar question:
Reverse / invert a dictionary mapping

Asked By: nilsinelabore

||

Answers:

You can first create another dict which reverses the mapping of the original dict, then sort based on that.

revd = {v:k for k, v in D.items()}
res = sorted(L, key=revd.get)
Answered By: Unmitigated

You can create a reverse mapping to map names to values instead:

R = dict(map(reversed, D.items()))
print(sorted(L, key=R.get))
Answered By: blhsing

A dictionary in python has two fields, key, and value.

dict{key: value}

The sort function doesn’t know what to look for when it’s sorting. You can create a normal function or a lambda function that returns the value based on which it should sort the list/dictionary and pass it in the key argument of the sort function.

like this

d.sort(key=lambda d:d[x]) 
# Set the value of x to 0 or 1 if you want to sort them by key or values respectively.

You can refer to this YouTube video

Answered By: Priyanshu Mallick
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.