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.
<span>from collections import Counter</span>
<span>words = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']</span>
<span>word_counts = Counter(words)</span>
<span>print(word_counts)</span>defaultdict – automatic dictionary values – defaultdict automatically creates a default value for missing keys.
<span>from collections import defaultdict</span>
<span>category_counts = defaultdict(int)</span>
<span>categories = ['fruit', 'fruit', 'vegetable', 'fruit']</span>
<span>for category in categories:</span>
<span> category_counts[category] += 1</span>
<span>print(category_counts)</span>deque – double‑ended queue – deque provides fast appends and pops from both ends, useful for simple caches.
<span>from collections import deque</span>
<span>cache = deque(maxlen=3)</span>
<span>cache.append('page1')</span>
<span>cache.append('page2')</span>
<span>cache.append('page3')</span>
<span>cache.append('page4') # automatically removes the oldest 'page1'</span>
<span>print(cache)</span>namedtuple – readable immutable tuples – namedtuple combines tuple immutability with named fields for easy access.
<span>from collections import namedtuple</span>
<span>Student = namedtuple('Student', ['name', 'age', 'grade'])</span>
<span>john = Student(name='John Doe', age=20, grade='A')</span>
<span>print(john.name, john.age, john.grade)</span>ChainMap – linked mappings – ChainMap merges multiple dictionaries into a single view.
<span>from collections import ChainMap</span>
<span>default_conf = {'theme': 'light', 'font_size': 12}</span>
<span>user_conf = {'theme': 'dark'}</span>
<span>combined_conf = ChainMap(user_conf, default_conf)</span>
<span>print(combined_conf['theme'], combined_conf['font_size'])</span>UserList, UserDict, UserString – custom containers – Subclass these classes to extend list, dict, or string behavior, such as limiting a list's length.
<span>from collections import UserList</span>
<span>class SafeList(UserList):</span>
<span> def append(self, item):</span>
<span> if len(self.data) < 5:</span>
<span> super().append(item)</span>
<span> else:</span>
<span> print("列表已满,无法添加更多元素。")</span>
<span>safe_list = SafeList([1, 2, 3])</span>
<span>safe_list.append(4)</span>
<span>safe_list.append(5)</span>
<span>safe_list.append(6) # attempts to add a sixth element</span>heapq – heap operations – heapq implements a min‑heap, useful for priority queues.
<span>import heapq</span>
<span>pq = []</span>
<span>heapq.heappush(pq, (3, '任务C'))</span>
<span>heapq.heappush(pq, (1, '任务A'))</span>
<span>heapq.heappush(pq, (2, '任务B'))</span>
<span>while pq:</span>
<span> priority, task = heapq.heappop(pq)</span>
<span> print(task, '优先级:', priority)</span>OrderedDict and LRU cache – Using OrderedDict you can implement a Least‑Recently‑Used cache.
<span>from functools import lru_cache</span>
<span>from collections import OrderedDict</span>
<span>class LRUCache:</span>
<span> def __init__(self, capacity):</span>
<span> self.capacity = capacity</span>
<span> self.cache = OrderedDict()</span>
<span> def get(self, key):</span>
<span> if key not in self.cache:</span>
<span> return -1</span>
<span> value = self.cache.pop(key)</span>
<span> self.cache[key] = value # move to end</span>
<span> return value</span>
<span> def put(self, key, value):</span>
<span> if key in self.cache:</span>
<span> self.cache.pop(key)</span>
<span> elif len(self.cache) == self.capacity:
<span> self.cache.popitem(last=False)</span>
<span> self.cache[key] = value</span>
<span># Example usage</span>
<span>cache = LRUCache(2)</span>
<span>cache.put(1, 1)</span>
<span>cache.put(2, 2)</span>
<span>print(cache.get(1)) # returns 1</span>
<span>cache.put(3, 3) # evicts key 2</span>
<span>print(cache.get(2)) # returns -1 (not found)</span>
<span>cache.put(4, 4) # evicts key 1</span>
<span>print(cache.get(1)) # returns -1 (not found)</span>
<span>print(cache.get(3)) # returns 3</span>
<span>print(cache.get(4)) # returns 4</span>Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.
