PYTHON
Frequency Counting with Python's collections.Counter
Master the `collections.Counter` in Python to efficiently count hashable objects, perfect for analyzing data frequencies in web applications, logs, and user activity.
from collections import Counter
# Counting occurrences in a list of items
fruits = ['apple', 'orange', 'banana', 'apple', 'grape', 'banana', 'apple']
fruit_counts = Counter(fruits)
print(f"Fruit counts: {fruit_counts}")
# Accessing count of a specific item
print(f"Count of 'apple': {fruit_counts['apple']}")
print(f"Count of 'mango' (non-existent): {fruit_counts['mango']}") # Returns 0
# Counting word frequencies in a string
sentence = "this is a test sentence this sentence is a test of frequency"
words = sentence.split()
word_counts = Counter(words)
print(f"Word counts: {word_counts}")
# Finding the most common items
most_common_words = word_counts.most_common(2) # Top 2 most common
print(f"Top 2 most common words: {most_common_words}")
# Updating a counter
another_batch_of_fruits = ['apple', 'pear', 'banana']
fruit_counts.update(another_batch_of_fruits)
print(f"Updated fruit counts: {fruit_counts}")
# Arithmetic operations on counters (union, intersection, difference)
counter1 = Counter(a=3, b=1)
counter2 = Counter(a=1, b=2)
# Addition (combines counts)
print(f"Counter addition: {counter1 + counter2}")
# Subtraction (subtracts counts, removes items if count <= 0)
print(f"Counter subtraction: {counter1 - counter2}")
# Intersection (min of corresponding counts)
print(f"Counter intersection: {counter1 & counter2}")
# Union (max of corresponding counts)
print(f"Counter union: {counter1 | counter2}")
How it works: This snippet showcases `collections.Counter`, a powerful subclass of `dict` designed for convenient and efficient frequency counting of hashable objects. It demonstrates how to initialize a `Counter` from a list or string, access individual item counts (returning 0 for non-existent items), and find the most common elements using `most_common()`. Additionally, it illustrates how to update counts with new data and perform arithmetic operations like addition, subtraction, intersection, and union directly on `Counter` objects, making it ideal for analytics and statistical tasks in web development.