Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How can I sort one list by values from another list in Python?
Sometimes you need to sort one list based on the corresponding values in another list. Python provides several efficient approaches using zip() and sorted() functions to achieve this.
Using zip() and sorted()
The most Pythonic way is to zip the lists together and sort by the reference list
# Two Lists
cars = ['BMW', 'Toyota', 'Audi', 'Tesla', 'Hyundai']
priorities = [2, 5, 1, 4, 3]
print("Original cars:", cars)
print("Priority values:", priorities)
# Sorting cars based on priorities
sorted_cars = [car for (priority, car) in sorted(zip(priorities, cars))]
print("\nSorted cars by priority:", sorted_cars)
Original cars: ['BMW', 'Toyota', 'Audi', 'Tesla', 'Hyundai'] Priority values: [2, 5, 1, 4, 3] Sorted cars by priority: ['Audi', 'BMW', 'Hyundai', 'Tesla', 'Toyota']
Using Dictionary Approach
You can create a dictionary mapping and then sort by values
# Two Lists
cars = ['BMW', 'Toyota', 'Audi', 'Tesla', 'Hyundai']
priorities = [2, 5, 1, 4, 3]
print("Original cars:", cars)
print("Priority values:", priorities)
# Create dictionary mapping
car_priority = {cars[i]: priorities[i] for i in range(len(cars))}
# Sort dictionary by values and extract keys
sorted_cars = [car for car, priority in sorted(car_priority.items(), key=lambda item: item[1])]
print("\nSorted cars by priority:", sorted_cars)
Original cars: ['BMW', 'Toyota', 'Audi', 'Tesla', 'Hyundai'] Priority values: [2, 5, 1, 4, 3] Sorted cars by priority: ['Audi', 'BMW', 'Hyundai', 'Tesla', 'Toyota']
Using sorted() with key Parameter
You can directly sort one list using the other as a key
# Two Lists
cars = ['BMW', 'Toyota', 'Audi', 'Tesla', 'Hyundai']
priorities = [2, 5, 1, 4, 3]
print("Original cars:", cars)
print("Priority values:", priorities)
# Sort cars using priorities as key
sorted_cars = sorted(cars, key=lambda x: priorities[cars.index(x)])
print("\nSorted cars by priority:", sorted_cars)
Original cars: ['BMW', 'Toyota', 'Audi', 'Tesla', 'Hyundai'] Priority values: [2, 5, 1, 4, 3] Sorted cars by priority: ['Audi', 'BMW', 'Hyundai', 'Tesla', 'Toyota']
Comparison
| Method | Performance | Best For |
|---|---|---|
zip() + sorted() |
O(n log n) | Most efficient and readable |
| Dictionary mapping | O(n log n) | When you need the mapping later |
index() method |
O(n² log n) | Simple cases (inefficient for large lists) |
Conclusion
Use zip() with sorted() for the most efficient solution. The dictionary approach is useful when you need to preserve the mapping relationship for further operations.
Advertisements
