Arduino_Sentinel
Arduino_Sentinel

Reputation: 819

Sort list using dictionary key values

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?

Upvotes: 2

Views: 107

Answers (2)

Adam Puza
Adam Puza

Reputation: 1529

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']

Upvotes: 1

cs95
cs95

Reputation: 403218

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']

Upvotes: 5

Related Questions