Skip to content
Advertisement

Sorting list based on dictionary keys in python

Is there a short way to sort a list based on the order of another dictionary keys?

suppose I have:

JavaScript

I want to sort the list to be ['a','b','c'] based on the order of dic keys.

Advertisement

Answer

You can create a lookup of keys versus their insertion order in dic. To do so you can write:

JavaScript

Using this you can write a simple lookup for the key argument of sorted to rank items based on order.

JavaScript

If there are values in lst that are not found in dic you should call get using a lambda so you can provide a default index. You’ll have to choose if you want to rank unknown items at the start or end.

Default to the start:

JavaScript

Default to the end:

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement