Using the collections Module for Concise Code
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 ...
Get Intuitive Python now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.