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 duplicates based on Kth element tuple list
- Python | Sort a tuple by its float element
- Python | Count occurrence of all elements of list in a tuple
- Python | Group tuple into list based on value
- Python | Replace tuple according to Nth tuple element
- Python | Sort lists in tuple
- Python | Last occurrence of some element in a list
- Python | Sort tuple list on basis of difference of elements
- Python | Check element for range occurrence
- Python | Counting Nth tuple element
- Python | Adding N to Kth tuple element
- Python | Element Occurrence in dictionary of list values
- Python | Maximum element in tuple list
- Python | Count occurrences of an element in a Tuple
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.