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?
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']
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments