

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 Questions & Answers
- First occurrence of True number in Python
- Python - First occurrence of one list in another
- Python program to sort a tuple by its float element
- How to group Python tuple elements by their first element?
- How to get First Element of the Tuple in C#?
- Count occurrence of all elements of list in a tuple in Python
- Sort HashMap based on keys in Java
- Sort lists in tuple in Python
- Python program to sort table based on given attribute index
- How to pop-up the first element from a Python tuple?
- Sort array based on presence of fields in objects JavaScript
- Program to sort out phrases based on their appearances in Python
- Last occurrence of some element in a list in Python
- Sort array based on another array in JavaScript
- Index of first occurrence in StringCollection in C#?
Advertisements