Python | Sort tuple based on occurrence of first element

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.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to Sort tuple based 
# on occurrence of first element
def sortOnOccurence(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(sortOnOccurence(lst))

chevron_right


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.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to Sort tuple based 
# on occurrence of first element
from collections import OrderedDict
  
def sortOnOccurence(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(sortOnOccurence(lst))

chevron_right


Output:

[(1, 'Jake', 'Cara', 2), (2, 'Bob', 1)]


My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.