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 | Element Occurrence in dictionary of list values
- Python | Count the elements in a list until an element is a Tuple
- Python | Check if element is present in tuple of tuples
- Python | Sort a list according to the second element in sublist
- Unpacking a Tuple in Python
- Python | Reversing a Tuple
- Python | tuple() Function
- Python | First occurrence of True number
- Python | Add the occurrence of each number as sublists
- Python | Percentage occurrence at index
- Python | Unpacking tuple of lists
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.