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.
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
Counteris 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
defaultdictreturns 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
OrderedDictpreserves 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
namedtuplecreates 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
23deque
dequeprovides 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
ChainMapgroups 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.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.
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.
