pythonbeginner
Collections Module Patterns
Use Counter, defaultdict, deque, namedtuple, and ChainMap from the collections module.
pythonPress ⌘/Ctrl + Shift + C to copy
from collections import Counter, defaultdict, deque, namedtuple, ChainMap
# Counter
words = ["apple", "banana", "apple", "cherry", "banana", "apple"]
counts = Counter(words)
print(counts.most_common(2)) # [('apple', 3), ('banana', 2)]
# Counter arithmetic
a = Counter("aabbc")
b = Counter("abcdd")
print(a + b) # Counter({'a': 3, 'b': 3, 'c': 2, 'd': 2})
# defaultdict
graph: dict[str, list[str]] = defaultdict(list)
edges = [("a", "b"), ("a", "c"), ("b", "c")]
for src, dst in edges:
graph[src].append(dst)
# deque with maxlen
recent: deque[str] = deque(maxlen=5)
for item in ["a", "b", "c", "d", "e", "f"]:
recent.append(item)
print(list(recent)) # ['b', 'c', 'd', 'e', 'f']
# namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(3, 4)
print(p.x, p.y) # 3 4
# ChainMap — layered config
defaults = {"color": "red", "size": "medium"}
user_prefs = {"color": "blue"}
config = ChainMap(user_prefs, defaults)
print(config["color"]) # blue
print(config["size"]) # mediumUse Cases
- counting
- graph adjacency lists
- LRU-style buffers
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
pythonbeginner
Dataclass with Validation
Python dataclass with __post_init__ field validation, type coercion, and descriptive error messages.
Best for: Data transfer objects
#dataclass#validation
pythonintermediate
Custom Context Manager
Context managers for resource management using both class-based and decorator approaches with error handling.
Best for: Database connection management
#context-manager#resource-management
pythonintermediate
Pytest Fixtures and Parametrize
Reusable pytest fixtures with scope control, parametrize for data-driven tests, and temporary resources.
Best for: Unit test setup
#pytest#testing
pythonintermediate
FastAPI Dependency Injection
Use FastAPI's dependency injection for database sessions, auth checks, and shared service logic.
Best for: Database session management
#fastapi#dependency-injection