Program to order tuples by list using Python

Introduction

While dealing with data science domain, we may come across the scenario where we have to order the elements based on the external input. The task is to order the input tuple based on the external element provided.

Program to order tuples by list using Python

Program

Approach 1

ip_list = [ ('alpha', 3 ), ('beta', 9), ('gamma', 1) ]
ex_list = ['gamma', 'beta', 'alpha']
print("The given list : "+str(ip_list))


#Using dict()
t_list = dict(ip_list)
output = [(key, t_list[key]) for key in ex_list]
print("The ordered tuple list: "+str(output))

Output:

Program to order tuples by list using Python Output 1

Approach 2

ip_list = [ ('alpha', 3 ), ('beta', 9), ('gamma', 1) ]
ex_list = ['gamma', 'beta', 'alpha']
print("The given list : "+str(ip_list))
# Using setdefault(), sorted() and lambda()
x = dict()
for key, ele in enumerate(ex_list):
    x.setdefault(ele, []).append(key)       
output = sorted(ip_list, key = lambda ele: x[ele[0]].pop())


print("The ordered tuple list: "+str(output))

Output:

Program to order tuples by list using Python Output 2

Explanation

Approach 1: We have used python in-built function dict() with list comprehension. The dict() method converts the given tuple to dictionary and list comprehension maps the keys to the values and return the output.

Approach 2: We have used python sorted() and setdefault() methods. The setdefault() methods creates the lookup table mapping elements of tuple to the indices. And then it is sorted using sorted() method.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.