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 a tuple by its float element
- Python | Count occurrence of all elements of list in a tuple
- Python | Last occurrence of some element in a list
- Python | Count occurrences of an element in a Tuple
- Python | Count the elements in a list until an element is a Tuple
- Python | Check if element is present in tuple of tuples
- Python | Element Occurrence in dictionary of list values
- Python | Sort a list according to the second element in sublist
- Python | Reversing a Tuple
- Unpacking a Tuple in Python
- Python | tuple() Function
- Python | Split tuple into groups of n
- Python | Find whether all tuple have same length
- Python | Unpacking tuple of lists
- Python | Convert a list into 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 firstname.lastname@example.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.