简体   繁体   中英

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM