Python program to unique keys count for Value in Tuple List

PythonServer Side ProgrammingProgramming

When it is required to get the count of unique keys for values in a list of tuple, it can be iterated over and the respective counts can be determined.

Below is a demonstration of the same −

Example

 Live Demo

import collections
my_result = collections.defaultdict(int)

my_list = [[('Hello', 'Hey')], [('Jane', 'Will')], [('William', 'John')], [('Hello', 'Hey')], [('z', 'q')]]
print("The list of list is :")
print(my_list)
for elem in my_list:
   my_result[elem[0]] += 1
print("The result is : ")
print(my_result)

Output

The list of list is :
[[('Hello', 'Hey')], [('Jane', 'Will')], [('William', 'John')], [('Hello', 'Hey')], [('z', 'q')]]
The result is :
defaultdict(<class 'int'>, {('Hello', 'Hey'): 2, ('Jane', 'Will'): 1, ('William', 'John'): 1, ('z', 'q'): 1})

Explanation

  • The required packages are imported.

  • A list of list of tuples is defined, that contains string and characters.

  • The list is displayed on the console.

  • The list is iterated over, and the first element is incremented by 1.

  • This result is displayed on the console.

raja
Published on 15-Apr-2021 12:57:57
Advertisements