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
Python program to Order Tuples using external List
When you need to reorder tuples based on an external list, you can use dictionary conversion and list comprehension. This technique is useful when you have key-value pairs as tuples and want to sort them according to a specific order defined in another list.
Example
Here's how to order tuples using an external list ?
my_list = [('Mark', 34), ('Will', 91), ('Rob', 23)]
print("The list of tuple is:")
print(my_list)
ordered_list = ['Will', 'Mark', 'Rob']
print("The ordered list is:")
print(ordered_list)
temp = dict(my_list)
my_result = [(key, temp[key]) for key in ordered_list]
print("The ordered tuple list is:")
print(my_result)
The list of tuple is:
[('Mark', 34), ('Will', 91), ('Rob', 23)]
The ordered list is:
['Will', 'Mark', 'Rob']
The ordered tuple list is:
[('Will', 91), ('Mark', 34), ('Rob', 23)]
How It Works
-
Convert to Dictionary: The list of tuples is converted to a dictionary using
dict()for fast lookup - List Comprehension: Iterate through the ordered list and create new tuples using dictionary values
- Key-Value Mapping: Each key from the ordered list is paired with its corresponding value from the dictionary
Alternative Approach Using Lambda
You can also use the sorted() function with a custom key ?
my_list = [('Mark', 34), ('Will', 91), ('Rob', 23)]
ordered_list = ['Will', 'Mark', 'Rob']
# Create index mapping for custom order
order_dict = {name: index for index, name in enumerate(ordered_list)}
# Sort using the custom order
my_result = sorted(my_list, key=lambda x: order_dict[x[0]])
print("The ordered tuple list is:")
print(my_result)
The ordered tuple list is:
[('Will', 91), ('Mark', 34), ('Rob', 23)]
Conclusion
Use dictionary conversion with list comprehension for simple reordering of tuples. For more complex sorting scenarios, consider using sorted() with custom key functions.
Advertisements
