PYTHON
Count Frequencies with collections.Counter
Discover how to easily count the frequency of items in a list or other iterables using Python's collections.Counter, ideal for data analysis and statistics in web projects.
from collections import Counter
# Example data: a list of tags from blog posts or products
tags = [
"python", "webdev", "django", "flask", "python",
"database", "webdev", "api", "python", "flask",
"javascript", "webdev", "api", "security", "django"
]
# Count the frequency of each tag
tag_counts = Counter(tags)
print("Tag Frequencies:")
for tag, count in tag_counts.most_common(): # .most_common() provides sorted list
print(f" - {tag}: {count}")
# Access count for a specific tag
print(f"
Frequency of 'python': {tag_counts['python']}")
# Find the top 3 most common tags
print("
Top 3 most common tags:")
for tag, count in tag_counts.most_common(3):
print(f" - {tag}: {count}")
How it works: This code snippet illustrates the use of collections.Counter to efficiently count the occurrences of hashable objects in a collection. It's particularly useful in web development for tasks like analyzing popular tags, tracking page views, or tallying user selections. Counter provides methods like most_common() to easily retrieve items sorted by their frequency, making data analysis straightforward and concise.