2

Lets say i have a list to sort of

list_values = ['key3', 'key0', 'key1', 'key4', 'key2']

And a order dict of

ordered_dict = OrderedDict([('key4', 0), ('key1', 1), ('key2', 2), ('key0', 3), ('key3', 4)])

How can i sort the list_values using the ordered_dict key accordingly?

i.e:- sorted_list = ['key4', 'key1', 'key2', 'key0', 'key3']

EDIT: Since almost all of the answers solves the problem, what is the most suitable and perfect pythonic way of doing this?

3
  • 1
    Re:Edit. Generally, non-lambda solutions are preferred. I could go into a breakdown of each solution, but it would be more convincing for you if you could just time the solutions on your data and accept the fastest one. Commented Jan 21, 2019 at 20:57
  • oh, yeah sure.. Commented Jan 21, 2019 at 20:59
  • Do note that list.sort is an in-place method, which is faster but also sorts the data in-place, so make sure to reset the list. Commented Jan 21, 2019 at 21:00

2 Answers 2

5

Call list.sort, passing a custom key:

list_values.sort(key=ordered_dict.get)    
list_values
# ['key4', 'key1', 'key2', 'key0', 'key3']

Alternatively, the non-in-place version is done using,

sorted(list_values, key=ordered_dict.get)
# ['key4', 'key1', 'key2', 'key0', 'key3']
Sign up to request clarification or add additional context in comments.

1 Comment

Well, this is the best answer so far. btw, in my case i will go with non-in-place option since i want to store the returned sorted list. Thank you @coldspeed
1

If we assume that list is subset of dict:

list_values = ['key3', 'key1']

ordered_dict = OrderedDict([('key4', 0), ('key1', 1), ('key2', 2), ('key0', 3), ('key3', 4)])

output = [v for v in ordered_dict if v in list_values]

print(output)

['key1', 'key3']

Example 2:

list_values = ['key3', 'key0', 'key1', 'key4', 'key2']

ordered_dict = OrderedDict([('key4', 0), ('key1', 1), ('key2', 2), ('key0', 3), ('key3', 4)])

output = [v for v in ordered_dict if v in list_values]

print(output)

['key4', 'key1', 'key2', 'key0', 'key3']

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.