Welcome back to Day 33 of your Python journey!
Today, we’re zooming in on three essential tools from Python’s collections
module:
Counter
defaultdict
OrderedDict
These are not just convenient—they’re powerful tools that make your code cleaner and more efficient.
🧮 1. Counter
— Counting Made Easy
Counter
is a subclass of dict
designed to count hashable objects (like strings, numbers, etc.). It’s perfect for tracking frequencies.
✅ Basic Example:
from collections import Counter
fruits = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']
fruit_count = Counter(fruits)
print(fruit_count)
🧪 Output:
Counter({'apple': 3, 'banana': 2, 'orange': 1})
🔍 Useful Methods:
fruit_count.most_common(2) # [('apple', 3), ('banana', 2)]
fruit_count['banana'] # 2
fruit_count['grape'] # 0 (not KeyError!)
📌 Real Use Case:
- Counting words in a document
- Counting votes
- Tracking product sales
🧰 2. defaultdict
— Say Goodbye to KeyErrors
defaultdict
lets you automatically assign a default value to new keys, avoiding the need to check if a key exists.
✅ Example with int
:
from collections import defaultdict
scores = defaultdict(int)
scores['Alice'] += 10
scores['Bob'] += 5
print(scores)
🧪 Output:
defaultdict(<class 'int'>, {'Alice': 10, 'Bob': 5})
🧵 Example with list
:
grouped = defaultdict(list)
grouped['fruits'].append('apple')
grouped['fruits'].append('banana')
grouped['veggies'].append('carrot')
print(grouped)
🧪 Output:
defaultdict(<class 'list'>, {'fruits': ['apple', 'banana'], 'veggies': ['carrot']})
📌 Real Use Case:
- Grouping data
- Building histograms
- Word frequency counters (with
int
)
📜 3. OrderedDict
— Ordered Dictionaries
Before Python 3.7, dictionaries did not preserve insertion order.
OrderedDict
fixed that.
Now in Python 3.7+, regular dict
maintains order — but OrderedDict
is still useful for:
- Reordering
- Comparing order
- LRU (Least Recently Used) cache implementations
✅ Example:
from collections import OrderedDict
od = OrderedDict()
od['a'] = 1
od['b'] = 2
od['c'] = 3
print(od)
🧪 Output:
OrderedDict([('a', 1), ('b', 2), ('c', 3)])
🔄 Reordering:
od.move_to_end('a') # Moves 'a' to the end
print(od)
💡 Summary Table
Feature | What It Does | When to Use |
---|---|---|
Counter |
Counts frequency of items | Word counts, inventory, stats |
defaultdict |
Auto-defaults missing keys | Grouping, counting, nested data |
OrderedDict |
Maintains insertion order | Order-sensitive data storage |
🧪 Mini Practice
1. Word Frequency Counter:
sentence = "hello world hello code"
# Use Counter to count words
2. Grouping Students by Grade:
students = [('A', 'John'), ('B', 'Lisa'), ('A', 'James')]
# Use defaultdict(list) to group names by grade
3. Reordering a Dict:
# Create OrderedDict and move one key to end
Top comments (0)