Write a Python program to Order Tuples using external List


This program takes a list of tuples, sorts it according to a specific order, and returns a new list of tuples with the sorted elements. Here's what happens step-by-step:

  • The val list is defined and initialized with 4 tuples.
  • The original val list is printed using the following line:
    • print("Original List : ", val)
  • The ord_list variable is defined and initialized with a list of 4 elements in the desired order.
  • A dictionary named temp is created from the val list using the dict function.
  • The res list is created using a list comprehension. The list comprehension iterates over the elements in ord_list and for each element, it retrieves its corresponding value from the temp dictionary and creates a tuple of the form (key, value). The resulting tuples are then appended to the res list:
    • res = [(key, temp[key]) for key in ord_list]
  • The res list is printed using the following line:
    • print("The Ordered Tuple List : " , res)

So the program takes a list of tuples, creates a dictionary from it, and returns a new list of tuples sorted according to the order specified in ord_list.

Source Code

val = [('B', 68), ('D', 70), ('A', 67), ('C', 69)]
print("Original List : ", val)
ord_list = ['A', 'B', 'C', 'D']
temp = dict(val)
res = [(key, temp[key]) for key in ord_list]
 
print("The Ordered Tuple List : " , res)

Output

Original List :  [('B', 68), ('D', 70), ('A', 67), ('C', 69)]
The Ordered Tuple List :  [('A', 67), ('B', 68), ('C', 69), ('D', 70)]


Example Programs