Member-only story
Python
Python Collections Module: Essential Tools for Efficient Coding
Harnessing the power of namedtuple, deque, ChainMap, Counter, OrderedDict, and defaultdict
Python’s collections module is a powerful tool that developers often overlook. It offers a variety of utilities that can help you write more concise and efficient code by reducing boilerplate and providing abstractions for common operations
In this article, we will explore six of the most useful data types from the collections module:
namedtuple()
— factory function for creating tuple subclasses with named fieldsdeque
— list-like container with fast appends and pops on either endChainMap
— dict-like class for creating a single view of multiple mappingsCounter
— dict subclass for counting hashable objectsOrderedDict
— dict subclass that remembers the order entries were addeddefaultdict
— dict subclass that calls a factory function to supply missing values
We’ll touch on each of them, providing a practical example with code, and then give examples of how they are used in the real world.
Let’s dive right in.
The code is on Deepnote.
namedtuple()
A practical use case for namedtuple
could be creating an account with the following information: name, balance, and currency.
from collections import namedtuple
# Define a namedtuple for representing a bank account
Account = namedtuple('Account', ['name', 'balance', 'currency'])
# Create an account
my_acc = Account(name='John Doe', balance=100.0, currency='USD')
# __repr__
print(my_acc) # Output: Account(name='John Doe', balance=100.0, currency='USD')
# Access the fields of the account using dot notation
print(my_acc.name) # Output: 'John Doe'
print(my_acc.balance) # Output: 100.0…