Fundamentals 11 min read

Master Python’s collections: Counter, defaultdict, deque, and more

This article provides a comprehensive overview of Python’s collections module, detailing its specialized container types such as Counter, defaultdict, OrderedDict, namedtuple, deque, and ChainMap, along with usage examples and key methods for each.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Master Python’s collections: Counter, defaultdict, deque, and more

The collections module offers specialized container types that serve as alternatives to Python’s built‑in dict, list, set, and tuple. It includes Counter, defaultdict, OrderedDict, namedtuple, deque, and ChainMap.

Counter

Counter

is a dict subclass for counting hashable objects.

>> import collections
>>> # count characters
>>> collections.Counter('hello world')
Counter({'l': 3, 'o': 2, 'h': 1, 'e': 1, ' ': 1, 'w': 1, 'r': 1, 'd': 1})
>>> # count words
>>> collections.Counter('hello world hello lucy'.split())
Counter({'hello': 2, 'world': 1, 'lucy': 1})

Common methods: elements(): iterator over elements repeating each as many times as its count. most_common([n]): list of the n most common elements and their counts. subtract(iterable-or-mapping): decrement counts using another iterable or mapping. update(iterable-or-mapping): increment counts from another iterable or mapping.

defaultdict

defaultdict

returns a new dictionary‑like object that provides a default value for missing keys via a factory function.

>> d = collections.defaultdict()
defaultdict(None, {})
>>> e = collections.defaultdict(str)
defaultdict(<class 'str'>, {})
>>> e['hello']
''
>>> e
defaultdict(<class 'str'>, {'hello': ''})
>>> fruit = collections.defaultdict(int)
>>> fruit['apple'] = 2
>>> fruit['banana']
0
>>> fruit
defaultdict(<class 'int'>, {'apple': 2, 'banana': 0})
>>> s = [('yellow',1),('blue',2),('yellow',3),('blue',4),('red',1)]
>>> d = collections.defaultdict(list)
>>> for k,v in s:
...     d[k].append(v)
>>> d
defaultdict(<class 'list'>, {'yellow': [1, 3], 'blue': [2, 4], 'red': [1]})

OrderedDict

OrderedDict

preserves the insertion order of keys.

>> o = collections.OrderedDict()
>>> o['k1'] = 'v1'
>>> o['k3'] = 'v3'
>>> o['k2'] = 'v2'
>>> o
OrderedDict([('k1', 'v1'), ('k3', 'v3'), ('k2', 'v2')])
>>> o['k1'] = 666
>>> o
OrderedDict([('k1', 666), ('k3', 'v3'), ('k2', 'v2')])

namedtuple

namedtuple

creates tuple subclasses with named fields.

>> Person = collections.namedtuple('Person', ['name', 'age', 'height'])
>>> lucy = Person('lucy', 23, 180)
>>> lucy
Person(name='lucy', age=23, height=180)
>>> lucy.name
'lucy'
>>> lucy.age
23

deque

deque

provides a thread‑safe double‑ended queue with O(1) appends and pops from both ends.

>> d = collections.deque(maxlen=10)
>>> d.extend('python')
>>> list(d)
['p', 'y', 't', 'h', 'o', 'n']
>>> d.append('e')
>>> d.appendleft('f')
>>> d.appendleft('g')
>>> d.appendleft('h')
>>> d
deque(['h', 'g', 'f', 'p', 'y', 't', 'h', 'o', 'n', 'e'], maxlen=10)
>>> d.appendleft('i')
>>> d
deque(['i', 'h', 'g', 'f', 'p', 'y', 't', 'h', 'o', 'n'], maxlen=10)

Key methods include append, appendleft, pop, popleft, extend, extendleft, clear, rotate, and others.

ChainMap

ChainMap

groups multiple dictionaries (or mappings) into a single view for lookup, preserving the order of the mappings.

>> d1 = {'apple': 1, 'banana': 2}
>>> d2 = {'orange': 2, 'apple': 3, 'pike': 1}
>>> combined = collections.ChainMap(d1, d2)
>>> combined
ChainMap({'apple': 1, 'banana': 2}, {'orange': 2, 'apple': 3, 'pike': 1})
>>> for k, v in combined.items():
...     print(k, v)
orange 2
apple 1
pike 1
banana 2
>>> combined['apple'] = 2  # modifies the first mapping
>>> combined
ChainMap({'apple': 2, 'banana': 2}, {'orange': 2, 'apple': 3, 'pike': 1})

Modifications affect only the first mapping in the chain; new keys are added there.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PythonCollectionsChainMapCounterdefaultdictdeque
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.