Appearance
collections
The collections
module is a built-in module in Python that provides various specialized container classes.
namedtuple
A namedtuple
allows you to create tuple-like objects with named fields, improving code readability. For example, a point in 2D space can be represented as:
python
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(1, 2)
print(p.x) # 1
print(p.y) # 2
This makes it easy to define custom data types that maintain tuple immutability while allowing attribute access.
deque
A deque
(double-ended queue) is an optimized list for fast appends and pops from both ends:
python
from collections import deque
q = deque(['a', 'b', 'c'])
q.append('x') # Add to the right
q.appendleft('y') # Add to the left
print(q) # deque(['y', 'a', 'b', 'c', 'x'])
defaultdict
A defaultdict
returns a default value when a key does not exist, eliminating the need for key existence checks:
python
from collections import defaultdict
dd = defaultdict(lambda: 'N/A')
dd['key1'] = 'abc'
print(dd['key1']) # 'abc'
print(dd['key2']) # 'N/A'
OrderedDict
An OrderedDict
maintains the order of keys based on insertion:
python
from collections import OrderedDict
od = OrderedDict([('a', 1), ('b', 2), ('c', 3)])
print(od) # OrderedDict([('a', 1), ('b', 2), ('c', 3)])
This is particularly useful for preserving the order of elements when iterating.
ChainMap
ChainMap
links multiple dictionaries, providing a single view of them. It’s useful for parameter lookup with priority:
python
from collections import ChainMap
import os, argparse
defaults = {'color': 'red', 'user': 'guest'}
parser = argparse.ArgumentParser()
parser.add_argument('-u', '--user')
parser.add_argument('-c', '--color')
namespace = parser.parse_args()
command_line_args = {k: v for k, v in vars(namespace).items() if v}
combined = ChainMap(command_line_args, os.environ, defaults)
print('color=%s' % combined['color'])
print('user=%s' % combined['user'])
Counter
A Counter
is a subclass of dict
designed for counting hashable objects:
python
from collections import Counter
c = Counter('programming')
print(c) # Counter({'g': 2, 'r': 2, 'm': 2, ...})
c.update('hello') # Update with new data
print(c)
Summary
The collections
module provides various specialized container classes that enhance Python's built-in types, allowing for more efficient and readable data manipulation.