Background
Although Python provides very flexible data structures such as lists and dictionaries, the <span>collections</span> module offers high-performance container data types that can significantly optimize code efficiency and readability. This article will delve into the six core tools within this module to help you write more elegant Python code and avoid reinventing the wheel.
Environment Setup
1import sys
2
3print('Python version:', sys.version.split('|')[0])
4# Python version: 3.11.11
namedtuple: Named Tuple
Traditional tuples access elements via indices, which reduces code readability:
1point = (2, 5)
2print(f"X: {point[0]}, Y: {point[1]}") # Low readability
namedtuple assigns field names to tuples.
1from collections import namedtuple
2
3# Create a named tuple type
4Point = namedtuple('Point', ['x', 'y'])
5p = Point(2, 5)
6
7print(p.x, p.y) # Intuitive access
8print(p._asdict()) # Convert to dictionary: {'x': 2, 'y': 5}
✅ Applicable scenarios: Database query results, coordinate points, and other lightweight data structures.
deque: Efficient Double-Ended Queue
Inserting/deleting at the head of a list has a time complexity of <span>O(n)</span>, while deque operations at both ends have a time complexity of <span>O(1)</span>.
1from collections import deque
2
3d = deque([1, 2, 3])
4d.appendleft(0) # Add to the left → deque([0, 1, 2, 3])
5d.extend([4, 5]) # Extend to the right → [0, 1, 2, 3, 4, 5]
6d.rotate(2) # Rotate right → [4, 5, 0, 1, 2, 3]
🔥 Performance comparison: Inserting at the head with a million elements.
- list.insert(0, x): Takes 2.1 seconds
- deque.appendleft(x): Takes 0.02 seconds
Counter: Element Counting Tool
Quickly count the frequency of elements in an iterable.
1from collections import Counter
2
3text = "python collections is powerful"
4word_count = Counter(text.split())
5
6print(word_count.most_common(2))
7# Output: [('python', 1), ('collections', 1)]
8
9# Mathematical operations
10c1 = Counter(a=3, b=1)
11c2 = Counter(a=1, b=2)
12print(c1 + c2) # Counter({'a': 4, 'b': 3})
💡 Advanced tip: The elements() method generates an iterator, and subtract() performs subtraction operations.
defaultdict: Smart Dictionary
Avoid KeyError exceptions by automatically initializing default values.
1from collections import defaultdict
2
3# Dictionary with list as values
4dd = defaultdict(list)
5dd['fruits'].append('apple') # No need for initialization
6print(dd['animals']) # Accessing a non-existent key returns an empty list []
7
8# Dictionary with counts as values
9count_dict = defaultdict(int)
10for char in "abracadabra":
11 count_dict[char] += 1
Supports any callable object: defaultdict(lambda: ‘N/A’)
ChainMap: Dictionary Aggregator
Merge multiple dictionaries without creating new objects.
1from collections import ChainMap
2
3dict1 = {'a': 1, 'b': 2}
4dict2 = {'b': 3, 'c': 4}
5
6chain = ChainMap(dict1, dict2)
7print(chain['b']) # Output: 2 (dict1 takes precedence)
8print(chain['c']) # Output: 4
9
10# Dynamically add a dictionary
11chain = chain.new_child({'d': 5})
🌟 Features: Customizable lookup order, original dictionaries modify in real-time.
OrderedDict: Ordered Dictionary
Although dict in Python 3.7+ is ordered, OrderedDict provides additional functionality.
1from collections import OrderedDict
2
3od = OrderedDict()
4od['z'] = 1
5od['a'] = 2
6print(list(od.keys())) # Maintains insertion order: ['z', 'a']
7
8# Special methods
9od.move_to_end('z') # Move key to the end, OrderedDict([('a', 2), ('z', 1)])
10od.popitem(last=False) # FIFO deletion, removes ('a', 2)
Related Articles
- Did you know that Python dictionaries are already ordered?
- Using partial functions in Python to generate different aggregation functions.
- Lambda anonymous functions in Python.
The above are some issues I encountered in practice, shared for everyone’s reference and learning. Feel free to follow our WeChat public account: DataShare, where we share valuable content from time to time.