Given a list of tuples, write a Python program to sort the list based on the occurrence of first element of tuples.
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
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.
[(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.
[(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