
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
Unique Keys Count for Value in Tuple List in Python
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
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.
Advertisements