Sort list using dictionary key values

Arduino_Sentinel

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?

cs95

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.

edited at
0

Comments

0 comments
Login to comment

Related

How do I sort a key:list dictionary by values in list?

Sort list of values in a dictionary

How to change set into list and sort by the key with alphabetically ordered values in a dictionary?

Python using dictionary list values to key match a dictionary

How to sort dictionary with list values?

How to convert list to dictionary using alpha as key and digit as values

Mapping dictionary key values in a list

Accessing the key of a dictionary with a list of values

convert dataframe to a dictionary with key and list of dictionary as values

How to sort the values of each key of dictionary python?

Swift how to sort array dictionary by key values

Create dictionary using max key values from another dictionary as keys, and lower values from original dictionary as list of values

Sort a list of dictionary with order of specific key

sort list of integers that are value to a key in dictionary python

How to sort embedded list of dictionary by key value?

Group the list of dictionary as list of values based on key

Sort a dictionary containing child dictionary, by using value of a key in the child dictionary

Sort by sum of values in a list for dictionary python

Sort an item in a list of tuples in the values of a dictionary with Python

Sort of dictionary values from keys in an ordered list

Split/Sort nested list into a dictionary based on values

how to sort values from a dictionary in a list

Python to sort summed dictionary list values

Sort dictionary based on values from a list

How to sort a list based on dictionary values?

Parameterize all key/value pairs in a dictionary mapping of key and list of values using pytest?

Using dictionary to modify list values

using lambda, filter for extracting values from a dictionary based on list key values

Sort list of function using sort with key in racket