Python Order Tuples by List (original) (raw)

Given a list of tuples, our task is to reorder it according to the sequence defined in another list. This can be useful in data processing, sorting, and mapping tasks.

**Example:

**Input = [('Gfg', 10), ('best', 3), ('CS', 8), ('Geeks', 7)], ord_list = ['Geeks', 'best', 'CS', 'Gfg']
**Output = [('Geeks', 7), ('best', 3), ('CS', 8), ('Gfg', 10)]

Using dict() + List Comprehension

Convert the list of tuples into a dictionary for fast key-value access, then use list comprehension to reorder tuples based on the given list sequence.

Python `

t = [('Gfg', 3), ('best', 9), ('CS', 10), ('Geeks', 2)] l = ['Geeks', 'best', 'CS', 'Gfg']

temp = dict(t) res = [(key, temp[key]) for key in l] print( res)

`

Output

[('Geeks', 2), ('best', 9), ('CS', 10), ('Gfg', 3)]

**Explanation:

Using setdefault() + sorted() + lambda

This method builds a position map for elements using setdefault() and then sorts tuples with sorted() and a lambda based on that predefined order.

Python `

t = [('Gfg', 3), ('best', 9), ('CS', 10), ('Geeks', 2)] l = ['Geeks', 'best', 'CS', 'Gfg']

temp = {} for key, ele in enumerate(l): temp.setdefault(ele, []).append(key)

res = sorted(t, key=lambda ele: temp[ele[0]].pop()) print( res)

`

Output

[('Geeks', 2), ('best', 9), ('CS', 10), ('Gfg', 3)]

**Explanation:

Using reduce() Function

This method uses functools.reduce() to iterate over the order list and sequentially accumulate tuples from the main list in the desired order.

Python `

from functools import reduce

t = [('Gfg', 3), ('best', 9), ('CS', 10), ('Geeks', 2)] l = ['Geeks', 'best', 'CS', 'Gfg']

res = reduce(lambda acc, key: acc + [ele for ele in t if ele[0] == key], l, []) print( res)

`

Output

[('Geeks', 2), ('best', 9), ('CS', 10), ('Gfg', 3)]

**Explanation: reduce(lambda acc, key: acc + [ele for ele in t if ele[0] == key], l, []): iterates through each element in l, finds matching tuples in t, and accumulates them in order.

Using lambda with sorted()

This method sorts the tuples based on the position of their first element in the reference list using a lambda function with sorted().

Python `

t = [('Gfg', 10), ('best', 3), ('CS', 8), ('Geeks', 7)] l = ['Geeks', 'best', 'CS', 'Gfg']

res = sorted(t, key=lambda x: l.index(x[0])) print(res)

`

Output

[('Geeks', 7), ('best', 3), ('CS', 8), ('Gfg', 10)]

**Explanation: sorted(t, key=lambda x: l.index(x[0])): sorts t based on each tuple’s first element’s position in l.

Using itemgetter()

This method sorts tuples based on a specific element index using itemgetter() from the operator module for cleaner and faster key access.

Python `

from operator import itemgetter

l1 = [('Gfg', 3), ('best', 9), ('CS', 10), ('Geeks', 2)] l2 = sorted(l1, key=itemgetter(1)) print(l2)

`

Output

[('Geeks', 2), ('Gfg', 3), ('best', 9), ('CS', 10)]

**Explanation: **sorted(l1, key=itemgetter(1)): sorts the list based on the second element (index 1) of each tuple.