Open In App

Python | Sort tuple based on occurrence of first element

Improve
Improve
Like Article
Like
Save
Share
Report

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



Last Updated : 02 May, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads