- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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']
Advertisements