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)]
- Python | Sort tuple list by Nth element of tuple
- Python - Remove first occurrence of K in Tuple
- Python | sort list of tuple based on sum
- Python | Replace tuple according to Nth tuple element
- Python | Remove duplicates based on Kth element tuple list
- Python | Count occurrence of all elements of list in a tuple
- Python - Raise elements of tuple as power to another tuple
- Python - Convert Tuple String to Integer Tuple
- Python - Convert Tuple to Tuple Pair
- Python - Flatten tuple of List to tuple
- Python - Convert Tuple Matrix to Tuple List
- Python | Sort a tuple by its float element
- Python - Sort by Frequency of second element in Tuple List
- Python | Group tuple into list based on value
- Python - Find first element by second in tuple List
- Python - Remove given character from first element of Tuple
- Python | First occurrence of True number
- Python | First character occurrence from rear String
- Python - Substitute K for first occurrence of elements
- Python | Last occurrence of some element in a list
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. 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.