John D
John D

Reputation: 295

how to re-order a list based on another one that has the same items in python

I have two list with the same items in both of them. I want to sort the second unordered list based on the ordering of the first one.


ordered_list = ["first_name", "last_name", "language", "gender", "country", ]

unordered_list = ["country", "gender", "first_name", "last_name", "language",] 

unordered_list.sort(key=ordered_list)

print(unordered_list)

PS: I have a looooonger list to work with, this is just an example.

GOAL: the unordered_list items need to be sorted exactly how items are ordered in ordered_list

Is there a better approach than the one above that doesn't work?

Upvotes: 1

Views: 118

Answers (1)

Mike67
Mike67

Reputation: 11342

Use the index as the key:

ordered_list = ["first_name", "last_name", "language", "gender", "country", ]

unordered_list = ["country", "gender", "first_name", "last_name", "language",] 

unordered_list.sort(key= lambda x: ordered_list.index(x))

print(unordered_list)

Output

['first_name', 'last_name', 'language', 'gender', 'country']

Upvotes: 2

Related Questions