Improving Python collections
This section is designed to showcase different ways to improve your coding methodology by using the various Python collections available to you. Not every collections datatype is represented, but some interesting use cases are explored for certain containers.
How to do it...
The following examples are separated by the particular collection they utilize. iPython will be used to interactively create these examples.
Default dictionaries
- For this example (
book_catalog.py
), we will create a simplified ordering scheme for book categories; thedefault_factory
will be an anonymous function that returns a string:

- The line 1 simply imports the
collections
module, allowing access to thedefaultdict
class. - The line 2 creates an instance of
defaultdict
. The argument for the factory is a simple string indicating that the selected item doesn't exist. - The lines 3 – line 6 create items for the dictionary.
- The line 7 prints the default representation of the dictionary.
- The line 8 is a...
- The line 1 simply imports the