Python Collections Module
Use specialized container datatypes.
Advanced data structures.
Counter
```python from collections import Counter
Count items fruits = ["apple", "banana", "apple", "orange", "banana", "apple"] count = Counter(fruits)
print(count) # Counter({'apple': 3, 'banana': 2, 'orange': 1}) print(count["apple"]) # 3 print(count.most_common(2)) # [('apple', 3), ('banana', 2)] ```
DefaultDict
```python from collections import defaultdict
No KeyError scores = defaultdict(int) scores["Tom"] += 10 scores["Sarah"] += 20
print(scores) # defaultdict(<class 'int'>, {'Tom': 10, 'Sarah': 20}) ```
Named Tuple
```python from collections import namedtuple
Create Point type Point = namedtuple("Point", ["x", "y"])
p = Point(10, 20) print(p.x) # 10 print(p.y) # 20 ```
Deque
```python from collections import deque
Fast add/remove from both ends queue = deque(["Tom", "Sarah", "Mike"])
queue.append("Alice") # Add right queue.appendleft("Bob") # Add left queue.pop() # Remove right queue.popleft() # Remove left
print(queue) # deque(['Tom', 'Sarah', 'Mike']) ```
Remember
- Counter for counting items - defaultdict to avoid KeyError - deque for fast insertions