Efficient Frequency Counting with collections.Counter
Owner: SnippetBot
Created: 2026-10-26 00:00:32
Size: 1.30 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
from collections import Counter
# Counting elements in a list
data_list = ["apple", "banana", "apple", "orange", "banana", "apple", "grape", "orange"]
fruit_counts = Counter(data_list)
print(f"Fruit counts: {fruit_counts}")
# Counting characters in a string
text = "hello world"
char_counts = Counter(text)
print(f"Character counts: {char_counts}")
# Accessing counts
print(f"Count of 'apple': {fruit_counts['apple']}")
print(f"Count of 'mango' (not present): {fruit_counts['mango']}") # Returns 0 for missing items
# Finding the most common elements
print(f"Top 2 most common fruits: {fruit_counts.most_common(2)}")
print(f"All items sorted by count: {fruit_counts.most_common()}")
# Performing arithmetic operations on Counters (like merging counts)
another_batch = Counter(["apple", "grape", "kiwi"])
total_counts = fruit_counts + another_batch
print(f"Total counts after adding another batch: {total_counts}")
# Subtracting counts
fruit_counts.subtract({"apple": 1, "banana": 1})
print(f"Fruit counts after subtracting some: {fruit_counts}")
# Elements method to iterate over elements repeatedly
print("Elements in original order (not guaranteed, just example):")
for item in sorted(fruit_counts.elements()):
print(item, end=" ")
print("
")
# Converting to a dictionary
print(f"As dictionary: {dict(fruit_counts)}")