pythonbeginner

Collections Module Patterns

Use Counter, defaultdict, deque, namedtuple, and ChainMap from the collections module.

python
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"])   # medium

Use Cases

  • counting
  • graph adjacency lists
  • LRU-style buffers

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.