Sort values in array by keys in another dictionary (python)

Viewed 29

Let's suppose I have an array that looks like this:

x=['Other', 'Physical Training', 'Math', 'English', 'Physics', 'Literature']

I need to sort it (not alphabetically) by keys in dictionary:

 y={'Math':0,
    'Physics':1,
    'Chemistry':2,
    'Biology':3,
    'English':4,
    'Literature':5,
    'History':6,
    'Physical Training':7,
    'Other':8}

Based on y, I need to sort x, so that the end result looks like this:

x_sorted=['Math', 'Physics', 'English', 'Literature', 'Physical Training', 'Other']

How do I reach this?

1 Answers

if x is a list, to sort inplace:

x.sort(key=y.get)
#['Math', 'Physics', 'English', 'Literature', 'Physical Training', 'Other']

to sort without changing x itself:

x_sorted = sorted(x, key=y.get)

if x is an array, convert to list first:

x = list(x)

if not applicable, please provide more context in the use of arrays over lists so we can help better.

Related