Python program to Order Tuples using external List


When it is required to order the tuples using an external list, the list comprehension, and ‘dict’ method can be used.

Below is the demonstration of the same −

Example

 Live Demo

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)

Output

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)]

Explanation

  • The list of tuple is defined, and is displayed on the console.

  • Another list is defined, and is displayed on the console.

  • The list of tuple is converted into a dictionary.

  • It is iterated over and the elements are stored in another list.

  • This results in an ordered tuple which is displayed as output on the console.

Updated on: 17-Apr-2021

215 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements