Python Practice › Tuple Programs › Program 63

Order tuples by an external list

EasyTuple Programs · 63 of 70

Write a Python program to order tuples by the order of their keys in another list.

Advertisement
Input
[("very", 8), ("i", 6), ("am", 5), ("happy", 0)], order ["i", "am", "very", "happy"]
Output
[('i', 6), ('am', 5), ('very', 8), ('happy', 0)]

Approach

  1. Sort by each key’s position in the order list.

Solution

Python
data = [("very", 8), ("i", 6), ("am", 5), ("happy", 0)]order = ["i", "am", "very", "happy"]position = {key: i for i, key in enumerate(order)}print(sorted(data, key=lambda t: position[t[0]]))
Output
[('i', 6), ('am', 5), ('very', 8), ('happy', 0)]

Line by line

Line 3

A position lookup dict is faster than calling order.index for every item.

Advertisement

Learn the concept

New to this topic? Read the lesson, then come back.

More tuple programs

← All 70 Tuple Programs