Is there a short way to sort a list based on the order of another dictionary keys?
suppose I have:
JavaScript
x
3
1
lst = ['b', 'c', 'a']
2
dic = { 'a': "hello" , 'b': "bar" , 'c': "foo" }
3
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
1
6
1
>>> lst = ['d', 'b', 'c', 'a']
2
>>> dic = {"a": "hello", "b": "bar", "c": "foo"}
3
>>> order = {k: i for i, k in enumerate(dic)}
4
>>> order
5
{'a': 0, 'b': 1, 'c': 2}
6
Using this you can write a simple lookup for the key
argument of sorted
to rank items based on order
.
JavaScript
1
3
1
>>> sorted(lst, key=order.get)
2
['a', 'b', 'c']
3
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
1
4
1
>>> lst = ['d', 'b', 'c', 'a']
2
>>> sorted(lst, key=lambda k: order.get(k, -1))
3
['d', 'a', 'b', 'c']
4
Default to the end:
JavaScript
1
4
1
>>> lst = ['d', 'b', 'c', 'a']
2
>>> sorted(lst, key=lambda k: order.get(k, len(order)))
3
['a', 'b', 'c', 'd']
4