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
Python - Occurrence counter in List of Records
In this article we will explain how to count the occurrences or repetition of elements in the given list of records using Python. Sometimes we need to make a count for the repeated number of items in the given dataset so this article will be helpful to solve these kinds of problems.
Understanding the Problem
The problem we have is to count the repeated items in the given list of records using the Python programming language. So basically we have to show the result of counts of the same or identical items in the given list of records. Let us understand this problem with an example:
Using Manual Dictionary Counting
The first approach uses a custom function that iterates through each record and maintains a dictionary to count occurrences ?
Algorithm Steps
Step 1 Define the function called occurrence_counter and pass the data and key inside the function as inputs.
Step 2 Then initiate a counter dictionary and this dictionary will be empty initially to store the result of the function.
Step 3 Now a loop is initiated over the values of the data dictionary. And inside the loop we will get the value of each key using the record.get() method.
Step 4 If the value is not already present inside the counter dictionary then we will add the count of 1. Otherwise increment the value by 1.
Step 5 Repeat the above steps for all the items in the data record.
Example
# Define the function to counter the repeated items
def occurrence_counter(data, key):
counter = {}
for record in data:
value = record.get(key)
if value is not None:
counter[value] = counter.get(value, 0) + 1
return counter
# Initialize the list of records
data = [
{'color_name': 'Cyan', 'code': '#00FFFF'},
{'color_name': 'Red', 'code': '#FF0000'},
{'color_name': 'Cyan', 'code': '#00FFFF'},
{'color_name': 'Red', 'code': '#FF0000'},
{'color_name': 'Blue', 'code': '#0000FF'},
]
# Define the key to count
key = 'color_name'
occurrences = occurrence_counter(data, key)
print("Occurrences counter for the given data:")
print(occurrences)
Occurrences counter for the given data:
{'Cyan': 2, 'Red': 2, 'Blue': 1}
Using collections.Counter
The second approach uses the Counter class from the collections module, which provides a more Pythonic solution ?
Algorithm Steps
Step 1 First step is to import the Counter class from the collections module of Python.
Step 2 Then define the function as occurrence_counter and pass two parameters as data and key in the function.
Step 3 Then we will initiate the empty counts object to store the desired result.
Step 4 A loop will be initiated in this step to traverse the attributes of the data one by one.
Step 5 Then we will extract the required value from the data record. And update the counts object accordingly.
Example
# Import the Counter class
from collections import Counter
# Define the function to count the occurrences
def occurrence_counter(data, key):
counts = Counter()
for record in data:
value = record.get(key)
if value is not None:
counts[value] += 1
return counts
# Initialize the list of data
data = [
{'color_name': 'Cyan', 'code': '#00FFFF'},
{'color_name': 'Blue', 'code': '#0000FF'},
{'color_name': 'Cyan', 'code': '#00FFFF'},
{'color_name': 'Red', 'code': '#FF0000'},
{'color_name': 'Blue', 'code': '#0000FF'},
]
# Define the key for which we have to make count
key = 'color_name'
# Call the function
occurrences = occurrence_counter(data, key)
print(occurrences)
Counter({'Cyan': 2, 'Blue': 2, 'Red': 1})
Comparison
| Method | Memory Usage | Readability | Performance |
|---|---|---|---|
| Manual Dictionary | Lower | Good | O(n) |
| collections.Counter | Slightly Higher | Excellent | O(n) |
Complexity Analysis
The time required to complete the execution of both the above codes is O(n), here n is the size of the given input list of records. As we have iterated the given record one time using the loop in both the codes to look up the required key. The space complexity for both the techniques is O(m), here m is the size of the unique elements in the record. As we are storing only unique elements to get the counts.
Conclusion
Both approaches effectively count occurrences in a list of records. Use collections.Counter for cleaner, more readable code, or manual dictionary counting when you need full control over the counting logic.
