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 −


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("The list after sorting by occurence is")


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)]


  • 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.