0

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.

1
  • {item: dic[item] for item in lst} Commented Oct 2, 2022 at 21:17

1 Answer 1

1

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']
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.