Introduction
Overview of all specialized container types in the collections module.
Container Types Summary
| Type | Description | Use Case |
|---|---|---|
namedtuple | Tuple with named fields | Lightweight objects |
deque | Double-ended queue | Fast append/pop |
ChainMap | Multiple dicts as one | Config lookup |
Counter | Dict for counting | Frequency analysis |
OrderedDict | Dict preserving order | Legacy Python < 3.7 |
defaultdict | Dict with defaults | Grouping data |
UserDict | Dict wrapper | Custom dict behavior |
UserList | List wrapper | Custom list behavior |
UserString | String wrapper | Custom string behavior |
UserDict Example
from collections import UserDict
class CaseInsensitiveDict(UserDict):
def __setitem__(self, key, value):
self.data[key.lower()] = value
def __getitem__(self, key):
return self.data[key.lower()]
Practice Problems
- Implement custom collection type
- Create case-insensitive dictionary
- Build LRU cache from OrderedDict
- Extend UserList with validation
- Implement string collection with methods