
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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.
Advertisements