Python - Unique keys count for Value in Tuple List

PythonServer Side ProgrammingProgramming

When it is required to get the count of the unique values in a list of tuple, ‘defaultdict’, ‘set’ operator and the ‘append’ method are used.

Example

Below is a demonstration of the same −

from collections import defaultdict

my_list = [(12, 32), (12, 21), (21, 32), (89, 21), (71, 21), (89, 11), (99, 10), (8, 23), (10, 23)]

print("The list is :")
print(my_list)

my_result = defaultdict(list)

for element in my_list:
   my_result[element[1]].append(element[0])

my_result = dict(my_result)

result_dictionary = dict()

for key in my_result:
   result_dictionary[key] = len(list(set(my_result[key])))

print("The resultant list is :")
print(result_dictionary)

Output

The list is :
[(12, 32), (12, 21), (21, 32), (89, 21), (71, 21), (89, 11), (99, 10), (8, 23), (10, 23)]
The resultant list is :
{32: 2, 21: 3, 11: 1, 10: 1, 23: 2}

Explanation

  • The required packages are imported into the environment.

  • A list of tuple is defined and is displayed on the console.

  • An empty dictionary is created.

  • The list is iterated over, and the second and first elements are appended to the dictionary.

  • This list is again converted to a dictionary.

  • Another empty dictionary is created.

  • The list is iterated over, and unique elements are obtained using ‘set’ operator.

  • It is converted to a list, and its length is assigned to a variable.

  • This is the output that is displayed on the console.

raja
Published on 08-Sep-2021 10:49:19
Advertisements