Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Python program to unique keys count for Value in Tuple List
When working with lists of tuples, you may need to count how many times each unique tuple appears. Python's collections.defaultdict provides an elegant solution for counting occurrences without manually checking if keys exist.
Using collections.defaultdict
The defaultdict(int) automatically initializes missing keys with a default value of 0, making counting operations simple ?
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)
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})
Alternative: Using Counter
The Counter class from collections provides a more direct approach for counting ?
from collections import Counter
my_list = [[('Hello', 'Hey')], [('Jane', 'Will')], [('William', 'John')], [('Hello', 'Hey')], [('z', 'q')]]
# Extract tuples from nested lists
tuples_only = [elem[0] for elem in my_list]
result = Counter(tuples_only)
print("Using Counter:")
print(result)
Using Counter:
Counter({('Hello', 'Hey'): 2, ('Jane', 'Will'): 1, ('William', 'John'): 1, ('z', 'q'): 1})
How It Works
The process involves these steps:
- Initialize counter: Create a defaultdict with int type (defaults to 0)
- Iterate through list: Loop through each nested list element
-
Access first tuple: Use
elem[0]to get the tuple from the inner list - Increment count: Add 1 to the count for that tuple key
Comparison
| Method | Import Required | Best For |
|---|---|---|
defaultdict(int) |
collections | Custom counting logic |
Counter |
collections | Simple counting tasks |
Conclusion
Use defaultdict(int) for flexible counting scenarios where you need custom logic. The Counter class provides a cleaner solution for straightforward counting operations with tuples.
Advertisements
