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 – Find occurrences for each value of a particular key
When working with a list of dictionaries, you may need to find how many times each value appears for a particular key. Python provides several approaches to count occurrences of values for a specific key.
Using collections.Counter
The most straightforward approach is using Counter to count occurrences ?
from collections import Counter
my_dict = [
{'pyt': 13, 'fun': 44},
{'pyt': 63, 'best': 15},
{'pyt': 24, 'fun': 34},
{'pyt': 47, 'best': 64},
{'pyt': 13, 'fun': 55} # Adding duplicate value for demonstration
]
print("The dictionary list is:")
print(my_dict)
my_key = 'pyt'
print(f"\nCounting occurrences for key: {my_key}")
# Extract values for the key and count occurrences
values = [d[my_key] for d in my_dict if my_key in d]
result = dict(Counter(values))
print("The result is:")
print(result)
The dictionary list is:
[{'pyt': 13, 'fun': 44}, {'pyt': 63, 'best': 15}, {'pyt': 24, 'fun': 34}, {'pyt': 47, 'best': 64}, {'pyt': 13, 'fun': 55}]
Counting occurrences for key: pyt
The result is:
{13: 2, 63: 1, 24: 1, 47: 1}
Using itertools.groupby
You can also use groupby after sorting the data by the target key ?
from itertools import groupby
my_dict = [
{'pyt': 13, 'fun': 44},
{'pyt': 63, 'best': 15},
{'pyt': 24, 'fun': 34},
{'pyt': 47, 'best': 64},
{'pyt': 13, 'fun': 55}
]
my_key = 'pyt'
# Sort by the key value first (required for groupby)
sorted_data = sorted(my_dict, key=lambda x: x[my_key])
# Group by key value and count occurrences
result = {key: len(list(group)) for key, group in groupby(sorted_data, key=lambda x: x[my_key])}
print("The result is:")
print(result)
The result is:
{13: 2, 24: 1, 47: 1, 63: 1}
Using Dictionary with Manual Counting
A simple manual approach using a dictionary to track counts ?
my_dict = [
{'pyt': 13, 'fun': 44},
{'pyt': 63, 'best': 15},
{'pyt': 24, 'fun': 34},
{'pyt': 47, 'best': 64},
{'pyt': 13, 'fun': 55}
]
my_key = 'pyt'
result = {}
for dictionary in my_dict:
if my_key in dictionary:
value = dictionary[my_key]
result[value] = result.get(value, 0) + 1
print("The result is:")
print(result)
The result is:
{13: 2, 63: 1, 24: 1, 47: 1}
Comparison
| Method | Best For | Performance |
|---|---|---|
Counter |
Simple counting tasks | Fastest |
groupby |
Already sorted data | Good (requires sorting) |
| Manual Dictionary | Custom logic needed | Good |
Conclusion
Use collections.Counter for the most efficient value counting. The manual dictionary approach offers flexibility, while groupby works best with pre-sorted data.
Advertisements
