In this python tuple program, we will order tuples by external list.
Steps to solve the program
- Take a list of tuples and a list by which we have to order tuples as input.
- Create a dictionary of a list of tuples.
- It will set words in the tuples as keys and numbers as their values.
- Use a for loop to iterate over words in the list by which we have to order the tuples.
- Now add the word and its value in the dictionary to another list using list comprehension i.e. loop inside the list.
- Print the output.
list1 = [('very',8),('i',6),('am',5),('happy',0)]
list2 = ['i','am','very','happy']
print("List of tuple: ",list1)
print("List: ",list2)
d = dict(list1)
result = [(key, d[key]) for key in list2]
print("Output list: ",result)
Output :
List of tuple: [('very', 8), ('i', 6), ('am', 5), ('happy', 0)]
List: ['i', 'am', 'very', 'happy']
Output list: [('i', 6), ('am', 5), ('very', 8), ('happy', 0)]