
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Sort tuple based on occurrence of first element in Python
When it is required to sort the tuple based on the occurrence of the first element, the dict.fromkeys method can be used.
A list can be used to store heterogeneous values (i.e data of any data type like integer, floating point, strings, and so on).
A list of tuple basically contains tuples enclosed in a list.
The 'dict.fromkeys' method will return a dictionary with a specific key and a value.
Below is a demonstration for the same −
Example
def sort_on_occurence(my_lst): my_dict = {} for i, j in my_lst: my_dict.setdefault(i, []).append(j) return([(i, *dict.fromkeys(j), len(j)) for i, j in my_dict.items()]) my_list = [(1, 'Harold'), (12, 'Jane'), (4, 'Paul'), (7, 'Will')] print("The list of tuples is") print(my_list) print("The list after sorting by occurence is") print(sort_on_occurence(my_list))
Output
The list of tuples is [(1, 'Harold'), (12, 'Jane'), (4, 'Paul'), (7, 'Will')] The list after sorting by occurence is [(1, 'Harold', 1), (12, 'Jane', 1), (4, 'Paul', 1), (7, 'Will', 1)]
Explanation
- A method named 'sort_on_occurence' is defined, that takes a list of tuple as parameter.
- A new dictionary is created.
- The list of tuple is iterated over, and default values are set inside the empty dictionary.
- A list of tuple is defined, and is displayed on the console.
- The function is called by passing the above defined list of tuple.
- This is the output that is displayed on the console.
- Related Articles
- First occurrence of True number in Python
- Python program to sort a tuple by its float element
- Python - First occurrence of one list in another
- Count occurrence of all elements of list in a tuple in Python
- How to group Python tuple elements by their first element?
- Sort lists in tuple in Python
- How to pop-up the first element from a Python tuple?
- How to get First Element of the Tuple in C#?
- Program to sort out phrases based on their appearances in Python
- Python program to sort table based on given attribute index
- Last occurrence of some element in a list in Python
- Sort HashMap based on keys in Java
- Program to sort given set of Cartesian points based on polar angles in Python
- Program to sort an array based on the parity values in Python
- Sort a List of Tuples in Increasing Order by the Last Element in Each Tuple using Python program

Advertisements