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:

lst = ['b', 'c', 'a']
dic = { 'a': "hello" , 'b': "bar" , 'c': "foo" }

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:

>>> lst = ['d', 'b', 'c', 'a']
>>> dic = {"a": "hello", "b": "bar", "c": "foo"}
>>> order = {k: i for i, k in enumerate(dic)}
>>> order
{'a': 0, 'b': 1, 'c': 2}

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

>>> sorted(lst, key=order.get)
['a', 'b', 'c']

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:

>>> lst = ['d', 'b', 'c', 'a']
>>> sorted(lst, key=lambda k: order.get(k, -1))
['d', 'a', 'b', 'c']

Default to the end:

>>> lst = ['d', 'b', 'c', 'a']
>>> sorted(lst, key=lambda k: order.get(k, len(order)))
['a', 'b', 'c', 'd']
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement