DEV Community

Cover image for Day 33/100: Counter, defaultdict, and OrderedDict in Python
 Rahul Gupta
Rahul Gupta

Posted on

Day 33/100: Counter, defaultdict, and OrderedDict in Python

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)
Enter fullscreen mode Exit fullscreen mode

🧪 Output:

Counter({'apple': 3, 'banana': 2, 'orange': 1})
Enter fullscreen mode Exit fullscreen mode

🔍 Useful Methods:

fruit_count.most_common(2)  # [('apple', 3), ('banana', 2)]
fruit_count['banana']      # 2
fruit_count['grape']       # 0 (not KeyError!)
Enter fullscreen mode Exit fullscreen mode

📌 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)
Enter fullscreen mode Exit fullscreen mode

🧪 Output:

defaultdict(<class 'int'>, {'Alice': 10, 'Bob': 5})
Enter fullscreen mode Exit fullscreen mode

🧵 Example with list:

grouped = defaultdict(list)
grouped['fruits'].append('apple')
grouped['fruits'].append('banana')
grouped['veggies'].append('carrot')

print(grouped)
Enter fullscreen mode Exit fullscreen mode

🧪 Output:

defaultdict(<class 'list'>, {'fruits': ['apple', 'banana'], 'veggies': ['carrot']})
Enter fullscreen mode Exit fullscreen mode

📌 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)
Enter fullscreen mode Exit fullscreen mode

🧪 Output:

OrderedDict([('a', 1), ('b', 2), ('c', 3)])
Enter fullscreen mode Exit fullscreen mode

🔄 Reordering:

od.move_to_end('a')  # Moves 'a' to the end
print(od)
Enter fullscreen mode Exit fullscreen mode

💡 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
Enter fullscreen mode Exit fullscreen mode

2. Grouping Students by Grade:

students = [('A', 'John'), ('B', 'Lisa'), ('A', 'James')]
# Use defaultdict(list) to group names by grade
Enter fullscreen mode Exit fullscreen mode

3. Reordering a Dict:

# Create OrderedDict and move one key to end
Enter fullscreen mode Exit fullscreen mode

Top comments (0)