An Overview of Python's collections Module: Counter, defaultdict, OrderedDict, namedtuple, deque, and ChainMap
This article introduces Python's collections module, explaining the purpose and usage of its specialized container types—including Counter, defaultdict, OrderedDict, namedtuple, deque, and ChainMap—along with their most common methods and practical code examples.
Python's collections module provides specialized container datatypes that serve as alternatives to the built‑in dict , list , set , and tuple .
Counter is a dict subclass for counting hashable objects. It supports methods such as elements() , most_common([n]) , subtract([iterable-or-mapping]) , and update([iterable-or-mapping]) . Example usage:
>> import collections
>>> collections.Counter('hello world')
Counter({'l': 3, 'o': 2, 'h': 1, 'e': 1, ' ': 1, 'w': 1, 'r': 1, 'd': 1})
>>> collections.Counter('hello world hello lucy'.split())
Counter({'hello': 2, 'world': 1, 'lucy': 1})defaultdict is a dict subclass that supplies a default value for missing keys via a factory function. Common factories are str , int , list , and dict :
>> d = collections.defaultdict()
defaultdict(None, {})
>>> e = collections.defaultdict(str)
defaultdict(<class 'str'>, {})
>>> e['hello']
''
>>> fruit = collections.defaultdict(int)
>>> fruit['apple'] = 2
>>> fruit['banana']
0OrderedDict preserves the insertion order of keys, unlike the regular dict (prior to Python 3.7). Updating an existing key retains its original position:
>> o = collections.OrderedDict()
>>> o['k1'] = 'v1'
>>> o['k3'] = 'v3'
>>> o['k2'] = 'v2'
OrderedDict([('k1', 'v1'), ('k3', 'v3'), ('k2', 'v2')])
>>> o['k1'] = 666
OrderedDict([('k1', 666), ('k3', 'v3'), ('k2', 'v2')])namedtuple creates tuple subclasses with named fields, allowing attribute access. Three definition styles are shown:
>> P1 = collections.namedtuple('Person1', ['name', 'age', 'height'])
>>> P2 = collections.namedtuple('Person2', 'name,age,height')
>>> P3 = collections.namedtuple('Person3', 'name age height')
>>> lucy = P1('lucy', 23, 180)
Person1(name='lucy', age=23, height=180)
>>> lucy.name
'lucy'
>>> lucy.age
23deque implements a double‑ended queue with O(1) appends and pops from both ends. It can be bounded with maxlen and provides methods such as append , appendleft , pop , popleft , extend , extendleft , clear , rotate , etc.
>> d = collections.deque(maxlen=10)
>>> d.extend('python')
deque(['p', 'y', 't', 'h', 'o', 'n'], maxlen=10)
>>> d.append('e')
>>> d.appendleft('f')
>>> d.appendleft('g')
>>> d.appendleft('h')
deque(['h', 'g', 'f', 'p', 'y', 't', 'h', 'o', 'n', 'e'], maxlen=10)ChainMap groups multiple dictionaries (or other mappings) into a single view. Lookups search each mapping in order, while updates affect only the first mapping. It also provides new_child() and parents for hierarchical composition.
>> d1 = {'apple': 1, 'banana': 2}
>>> d2 = {'orange': 2, 'apple': 3, 'pike': 1}
>>> combined = collections.ChainMap(d1, d2)
ChainMap({'apple': 1, 'banana': 2}, {'orange': 2, 'apple': 3, 'pike': 1})
>>> combined['apple']
1
>>> combined['apple'] = 2 # updates only the first dict
>>> combined
ChainMap({'apple': 2, 'banana': 2}, {'orange': 2, 'apple': 3, 'pike': 1})Overall, the collections module equips Python developers with efficient, ready‑made container types that simplify common data‑handling patterns.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.