How can I sort one list by values from another list in Python?


We can sort a list by values from another list by setting up the 2nd list as index numbers for the values in the 1st List in sorted order.

Sort a List by values from another list

Example

In this example, we will sort a list by values from another list i.e. the 2nd list will have the index in the order in which they are placed in sorted order −

# Two Lists list1 = ['BMW', 'Toyota', 'Audi', 'Tesla', 'Hyundai'] list2 = [2, 5, 1, 4, 3] print("List1 = \n",list1) print("List2 (indexes) = \n",list2) # Sorting the List1 based on List2 res = [val for (_, val) in sorted(zip(list2, list1), key=lambda x: x[0])] print("\nSorted List = ",res)

Output

List1 = 
 ['BMW', 'Toyota', 'Audi', 'Tesla', 'Hyundai']
List2 (indexes) = 
 [2, 5, 1, 4, 3]

Sorted List =  ['Audi', 'BMW', 'Hyundai', 'Tesla', 'Toyota']

Sort a list by values from another list using Dictionary

Example

In this example, we will sort a list by values another list. We will add both the lists in a Dictionary and then usethe key value in Dictionary with lambda to sort.

# Two Lists list1 = ['BMW', 'Toyota', 'Audi', 'Tesla', 'Hyundai'] list2 = [2, 5, 1, 4, 3] print("List1 = \n",list1) print("List2 (indexes) = \n",list2) # Blank dictionary newDict = {} # Blank list outList = [] # Both the lists in our dictionary newDict newDict = {list1[i]: list2[i] for i in range(len(list2))} # Sorting using the sorting() based on key and values # Using lambda as well s = {k: v for k, v in sorted(newDict.items(), key=lambda item: item[1])} # Element addition in the list for i in s.keys(): outList.append(i) print("\nSorted List = \n",outList)

Output

List1 = 
 ['BMW', 'Toyota', 'Audi', 'Tesla', 'Hyundai']
List2 (indexes) = 
 [2, 5, 1, 4, 3]

Sorted List = 
['Audi', 'BMW', 'Hyundai', 'Tesla', 'Toyota']

Updated on: 16-Sep-2022

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements