Using the collections Module for Concise Code

Intuitive Python β€” by David Muller (16 / 41)

The Pragmatic Programmers
The Pragmatic Programmers

--

πŸ‘ˆ Chapter 2 Shifting Up with the Standard Library | TOC | Creating Temporary Workspaces with tempfile πŸ‘‰

The collections standard library module is a standby for many Python developers. It provides a number of utilities (particularly defaultdict, Counter, and namedtuple) that help reduce boilerplate code and make it possible to write concise Python. After you read through this section on collections, you will be familiar with some of the utilities in the module and be prepared to include them in your projects.

Write Concise Code with defaultdict

defaultdict is a convenience provided by the collections module. defaultdict allows you to add values to dictionaries concisely and reduce boilerplate code.

Consider, for example, if you had a program that used a dict to map file owners to files. The following script takes a list of (owner, file_name) pairs and collects them in a dictionary with owners as keys and lists of file names as values:

file_owners.py

​ files = [
​ (​"Jack"​, ​"hill.txt"​),
​ (​"Jill"​, ​"water.txt"​),
​ (​"Jack"​, ​"crown.txt"​),
​ ]
​
​ owner_to_files = {}
​ ​for​ owner, file_name ​in​ files:
​ ​if​ owner ​not​ ​in​ owner_to_files:
​ owner_to_files[owner] = []
​ owner_to_files[owner].append(file_name)
​
​ ​print​(owner_to_files)

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.