Python collections module: Counter, defaultdict, deque, namedtuple, ChainMap, custom containers, heapq, and LRU cache examples
This article introduces several useful classes from Python's collections module—including Counter, defaultdict, deque, namedtuple, ChainMap, UserList/UserDict/UserString, as well as heapq and an OrderedDict‑based LRU cache—explaining their purposes and providing ready‑to‑run code examples for each.
Counter – counting elements – Counter tracks how many times each element appears, useful for frequency analysis.
from collections import Counter
words = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']
word_counts = Counter(words)
print(word_counts)defaultdict – automatic dictionary values – defaultdict automatically creates a default value for missing keys.
from collections import defaultdict
category_counts = defaultdict(int)
categories = ['fruit', 'fruit', 'vegetable', 'fruit']
for category in categories:
category_counts[category] += 1
print(category_counts)deque – double‑ended queue – deque provides fast appends and pops from both ends, useful for simple caches.
from collections import deque
cache = deque(maxlen=3)
cache.append('page1')
cache.append('page2')
cache.append('page3')
cache.append('page4') # automatically removes the oldest 'page1'
print(cache)namedtuple – readable immutable tuples – namedtuple combines tuple immutability with named fields for easy access.
from collections import namedtuple
Student = namedtuple('Student', ['name', 'age', 'grade'])
john = Student(name='John Doe', age=20, grade='A')
print(john.name, john.age, john.grade)ChainMap – linked mappings – ChainMap merges multiple dictionaries into a single view.
from collections import ChainMap
default_conf = {'theme': 'light', 'font_size': 12}
user_conf = {'theme': 'dark'}
combined_conf = ChainMap(user_conf, default_conf)
print(combined_conf['theme'], combined_conf['font_size'])UserList, UserDict, UserString – custom containers – Subclass these classes to extend list, dict, or string behavior, such as limiting a list's length.
from collections import UserList
class SafeList(UserList):
def append(self, item):
if len(self.data) < 5:
super().append(item)
else:
print("列表已满,无法添加更多元素。")
safe_list = SafeList([1, 2, 3])
safe_list.append(4)
safe_list.append(5)
safe_list.append(6) # attempts to add a sixth elementheapq – heap operations – heapq implements a min‑heap, useful for priority queues.
import heapq
pq = []
heapq.heappush(pq, (3, '任务C'))
heapq.heappush(pq, (1, '任务A'))
heapq.heappush(pq, (2, '任务B'))
while pq:
priority, task = heapq.heappop(pq)
print(task, '优先级:', priority)OrderedDict and LRU cache – Using OrderedDict you can implement a Least‑Recently‑Used cache.
from functools import lru_cache
from collections import OrderedDict
class LRUCache:
def __init__(self, capacity):
self.capacity = capacity
self.cache = OrderedDict()
def get(self, key):
if key not in self.cache:
return -1
value = self.cache.pop(key)
self.cache[key] = value # move to end
return value
def put(self, key, value):
if key in self.cache:
self.cache.pop(key)
elif len(self.cache) == self.capacity:
self.cache.popitem(last=False)
self.cache[key] = value
# Example usage
cache = LRUCache(2)
cache.put(1, 1)
cache.put(2, 2)
print(cache.get(1)) # returns 1
cache.put(3, 3) # evicts key 2
print(cache.get(2)) # returns -1 (not found)
cache.put(4, 4) # evicts key 1
print(cache.get(1)) # returns -1 (not found)
print(cache.get(3)) # returns 3
print(cache.get(4)) # returns 4Test Development Learning Exchange
Test Development Learning Exchange
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.