Python | Sort tuple based on occurrence of first element
Last Updated :
02 May, 2023
Given a list of tuples, write a Python program to sort the list based on the occurrence of first element of tuples. Examples:
Input : [(1, 'Jake'), (2, 'Bob'), (1, 'Cara')]
Output : [(1, 'Jake', 'Cara', 2), (2, 'Bob', 1)]
Input : [('b', 'ball'), ('a', 'arm'), ('b', 'b'), ('a', 'ant')]
Output : [('a', 'arm', 'ant', 2), ('b', 'ball', 'b', 2)]
Approach #1 : using dict.fromkeys The fromkeys() method returns a new dictionary with the given sequence of elements as the keys of the dictionary. Now once we store the new dictionary in 'dct' we can easily iterate over 'dct' elements and output the desired elements.
Python3
# Python3 program to Sort tuple based
# on occurrence of first element
def sortOnOccurrence(lst):
dct = {}
for i, j in lst:
dct.setdefault(i, []).append(j)
return([(i, *dict.fromkeys(j), len(j))
for i, j in dct.items()])
# Driver code
lst = [(1, 'Jake'), (2, 'Bob'), (1, 'Cara')]
print(sortOnOccurrence(lst))
Output:[(1, 'Cara', 'Jake', 2), (2, 'Bob', 1)]
Approach #2 : OrderedDict from collections module This method is an alternative to the above-mentioned approach. We follow similar approach but with a slight change, concatenate the tuples while iterating through 'dct' using OrderedDict.
Python3
# Python3 program to Sort tuple based
# on occurrence of first element
from collections import OrderedDict
def sortOnOccurrence(lst):
dct = {}
for i, j in lst:
dct.setdefault(i, []).append(j)
return([(k, ) + tuple(OrderedDict.fromkeys(v)) + (len(v), )
for k, v in dct.items()])
# Driver code
lst = [(1, 'Jake'), (2, 'Bob'), (1, 'Cara')]
print(sortOnOccurrence(lst))
Output:[(1, 'Jake', 'Cara', 2), (2, 'Bob', 1)]
Approch #3: Using lambda function
In this approach, the lambda function is used to create a one-line function to sort the list based on the occurrence of the first element in each tuple. The code creates a dictionary dct to store the first element as key and a list of second elements as value. It then returns a list comprehension that extracts the unique values from the value list of each key using dict.fromkeys(), combines them with the key, and appends the length of the value list to the end of the tuple.
Python3
sortOnOccurrence = lambda lst: [(i, *dict.fromkeys(j), len(j)) for i,j in {i:[j[1] for j in lst if j[0]==i] for i in set(map(lambda x: x[0], lst))}.items()]
# Driver code
lst = [(1, 'Jake'), (2, 'Bob'), (1, 'Cara')]
print(sortOnOccurrence(lst))
Output[(1, 'Jake', 'Cara', 2), (2, 'Bob', 1)]
Time Complexity: O(nlogn), due to the sorting operation at the end of the function
Space Complexity: O(n), where n is the number of elements in the input list
Similar Reads
Python - Sort Tuple List by Nth Element of Tuple We are given list of tuple we need to sort tuple by Nth element of each tuple. For example d = [(1, 5), (3, 2), (2, 8), (4, 1)] and k=1 we need to sort by 1st element of each tuple so that output for given list should be [(4, 1), (3, 2), (1, 5), (2, 8)]Using sorted() with lambdasorted() function wit
3 min read
Python - Sort by Frequency of second element in Tuple List Given list of tuples, sort by frequency of second element of tuple. Input : test_list = [(6, 5), (1, 7), (2, 5), (8, 7), (9, 8), (3, 7)] Output : [(1, 7), (8, 7), (3, 7), (6, 5), (2, 5), (9, 8)] Explanation : 7 occurs 3 times as 2nd element, hence all tuples with 7, are aligned first. Input : test_l
6 min read
Python | Check if element is present in tuple of tuples Sometimes the data that we use is in the form of tuples and often we need to look into the nested tuples as well. The common problem that this can solve is looking for missing data or na value in data preprocessing. Let's discuss certain ways in which this can be performed. Method #1: Using any() an
4 min read
Sort Tuple of Lists in Python The task of sorting a tuple of lists involves iterating through each list inside the tuple and sorting its elements. Since tuples are immutable, we cannot modify them directly, so we must create a new tuple containing the sorted lists. For example, given a tuple of lists a = ([2, 1, 5], [1, 5, 7], [
3 min read
Removing Tuples from a List by First Element Value - Python In this problem we need to delete tuples based on a specific condition related to their first element. For example: We are given the list data = [("GeeksforGeeks", "Python", 1000), ("CodingForAll", "Java", 1200)] and we need to remove all tuples where the first element is "GeeksforGeeks", the desire
3 min read
Python - Filter Tuples by Kth element from List Given a list of tuples, filter by Kth element presence in List. Input : test_list = [("GFg", 5, 9), ("is", 4, 3), ("best", 10, 29)], check_list = [4, 2, 3, 10], K = 2 Output : [('is', 4, 3)] Explanation : 3 is 2nd element and present in list, hence filtered tuple. Input : test_list = [("GFg", 5, 9),
5 min read