Skip to content
Related Articles

Related Articles

Python | Sort tuple based on occurrence of first element
  • Last Updated : 08 Apr, 2019

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 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))
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 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))
Output:
[(1, 'Jake', 'Cara', 2), (2, 'Bob', 1)]

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course

My Personal Notes arrow_drop_up
Recommended Articles
Page :