Sort tuple based on occurrence of first element in Python

PythonServer Side ProgrammingProgramming

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

Live Demo

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.
raja
Published on 13-Mar-2021 05:30:44
Advertisements