PYTHON
Count Frequencies of Items with collections.Counter
Easily count the occurrences of items in a list or sequence using Python's collections.Counter, perfect for analyzing log data, keywords, or web requests.
from collections import Counter
# Example 1: Count HTTP status codes from a web server log
access_logs = [
"GET /home 200", "POST /login 200", "GET /products 200",
"GET /error 404", "GET /admin 403", "GET /home 200",
"GET /products 200", "GET /search?q=python 200", "GET /error 404"
]
status_codes = [log.split()[-1] for log in access_logs]
status_counts = Counter(status_codes)
print(f"HTTP Status Code Counts: {status_counts}")
# Output: Counter({'200': 5, '404': 2, '403': 1})
# Example 2: Find the most common accessed URLs (after parsing)
urls = ["/home", "/products", "/home", "/admin", "/products", "/products"]
url_counts = Counter(urls)
print(f"Most common URLs: {url_counts.most_common(2)}") # Top 2
# Output: [('/products', 3), ('/home', 2)]
# Example 3: Combining multiple counters (e.g., from different servers)
server1_errors = Counter({'404': 10, '500': 3})
server2_errors = Counter({'404': 5, '403': 2, '500': 1})
total_errors = server1_errors + server2_errors
print(f"Combined Error Counts: {total_errors}")
# Output: Counter({'404': 15, '500': 4, '403': 2})
How it works: `collections.Counter` is a specialized dictionary subclass for counting hashable objects. It's incredibly useful for frequency analysis tasks common in web development, such as parsing access logs to count status codes, identifying popular URLs, or tracking user actions. It provides convenient methods like `most_common()` to retrieve the most frequent items and supports arithmetic operations for combining counts.