Fundamentals 11 min read

Master Python’s Powerful Containers: Counter, defaultdict, OrderedDict, deque & ChainMap

This article introduces Python’s collections module as a versatile alternative to built‑in containers, detailing the purpose, key methods, and practical code examples for Counter, defaultdict, OrderedDict, namedtuple, deque, and ChainMap, helping developers choose the right specialized container for their tasks.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Master Python’s Powerful Containers: Counter, defaultdict, OrderedDict, deque & ChainMap

Overview of the collections module

The collections module provides specialized container datatypes that serve as alternatives to the built‑in dict, list, set, and tuple, offering additional functionality and performance benefits.

Counter

Counter

is a subclass of dict designed for counting hashable objects. It returns a mapping where elements are keys and their frequencies are values.

import collections
# Count characters
collections.Counter('hello world')
# Count words
collections.Counter('hello world hello lucy'.split())

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 an iterable or mapping. update([iterable-or-mapping]): increment counts from an iterable or another mapping.

Examples of arithmetic operations:

c1 = collections.Counter('hello world'.split())
c2 = collections.Counter('hello lucy'.split())
c1 + c2          # Counter({'hello': 2, 'world': 1, 'lucy': 1})
c1 - c2          # Counter({'world': 1})
c1.clear()

defaultdict

defaultdict

is a subclass of dict that accepts a default_factory function. When a missing key is accessed, the factory supplies a default value instead of raising KeyError.

d = collections.defaultdict()
e = collections.defaultdict(str)
e['hello']   # returns ''
fruit = collections.defaultdict(int)
fruit['apple'] = 2
fruit['banana']   # returns 0

Typical factories are str, int, list, or dict, each producing an empty instance of the corresponding type.

OrderedDict

OrderedDict

preserves the insertion order of keys, unlike the regular dict (prior to Python 3.7). Updating an existing key does not change its position.

o = collections.OrderedDict()
o['k1'] = 'v1'
o['k3'] = 'v3'
o['k2'] = 'v2'
o['k1'] = 666   # value updated, order unchanged

namedtuple

namedtuple

creates tuple subclasses with named fields, allowing attribute‑style access.

P1 = collections.namedtuple('Person1', ['name','age','height'])
lucy = P1('lucy', 23, 180)
lucy.name   # 'lucy'
lucy.age    # 23

deque

deque

implements a double‑ended queue optimized for O(1) appends and pops from both ends. It can be bounded with a maxlen parameter.

d = collections.deque(maxlen=10)
d.extend('python')
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)

Key methods include append, appendleft, pop, popleft, clear, extend, extendleft, rotate, reverse, and the maxlen attribute.

ChainMap

ChainMap

groups multiple dictionaries (or mappings) into a single view. Lookups search each mapping in order; updates affect only the first mapping.

d1 = {'apple':1,'banana':2}
d2 = {'orange':2,'apple':3,'pike':1}
combined = collections.ChainMap(d1, d2)
combined['apple']   # 1
combined['apple'] = 2   # updates d1

Methods such as new_child() and the parents attribute allow dynamic stacking of mappings.

These containers enable more expressive and efficient data handling in Python programs.

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.

PythonCollectionsData StructuresChainMapCounterdefaultdictdeque
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.