Q:

Python program to order tuples by list

0

Example:

tuple = ("python", "includehelp", 43, 54.23)

List is a sequence data type. It is mutable as its values in the list can be modified. It is a collection of ordered set of values enclosed in square brackets [].

Order Tuples by List

We are given a list of tuples and a sorting list. We will create a python program for sorting list of tuples based on the values of the sorting list.

Input:
tupList = [('l', 5), ('k', 2), ('a', 1), ('e', 6)], sortList = ['l', 'a', 'k', 'e']

Output:
[('l', 5), ('a', 1), ('k', 2), ('e', 6)]

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Method 1:

A method to sort the list of tuples based on a list is by creating an empty dictionary and storing all list elements as keys with empty value. Then feed values to the dictionary.

This is done using a combination of setdefault() + sorted() + lambda function.

Program:

# Python program to order tuples by list

# Creating and printing tuple list and list 
tupList = [('l', 5), ('k', 2), ('a', 1), ('e', 6)]

print("The original list is : " + str(tupList))

sortingList = ['l', 'a', 'k', 'e']
print("The sorting list is " + str(sortingList))

# Sorting tuple list based on Sorting list 
valDict = dict()
for key, ele in enumerate(sortingList):
	valDict.setdefault(ele, []).append(key)	
sortedList = sorted(tupList, key = lambda ele: valDict[ele[0]].pop())

# Printing sorted List 
print("The ordered tuple list based on tuple list: " + str(sortedList))

Output:

The original list is : [('l', 5), ('k', 2), ('a', 1), ('e', 6)]
The sorting list is ['l', 'a', 'k', 'e']
The ordered tuple list based on tuple list: [('l', 5), ('a', 1), ('k', 2), ('e', 6)]

Method 2:

Another method to sort the list of tuples is by creating a dictionary with values of the list of tuples. Then, we will use list comprehension to store the values of the dictionary sorted by using sorting list.

Program:

# Python program to order list of tuples by sorted list

# creating and printing initial lists
tupList = [('l', 5), ('k', 2), ('a', 1), ('e', 6)]

print("The original list is : " + str(tupList))
sortingList = ['l', 'a', 'k', 'e']

print("The sorting list is " + str(sortingList))

# Sorting list of tuple 
Dic = dict(tupList)
sortedTupList = [(key, Dic[key]) for key in sortingList]

# Printing sorted List 
print("The ordered tuple list : " + str(sortedTupList))

Output:

The original list is : [('l', 5), ('k', 2), ('a', 1), ('e', 6)]
The sorting list is ['l', 'a', 'k', 'e']
The ordered tuple list : [('l', 5), ('a', 1), ('k', 2), ('e', 6)]

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now