Path: blob/master/12-Advanced Python Modules/00-Collections-Module.ipynb
666 views
Collections Module
The collections module is a built-in module that implements specialized container data types providing alternatives to Python’s general purpose built-in containers. We've already gone over the basics: dict, list, set, and tuple.
Now we'll learn about the alternatives that the collections module provides.
Counter
Counter is a dict subclass which helps count hashable objects. Inside of it elements are stored as dictionary keys and the counts of the objects are stored as the value.
Let's see how it can be used:
Counter() with lists
Counter with strings
Counter with words in a sentence
Common patterns when using the Counter() object
defaultdict
defaultdict is a dictionary-like object which provides all methods provided by a dictionary but takes a first argument (default_factory) as a default data type for the dictionary. Using defaultdict is faster than doing the same using dict.set_default method.
A defaultdict will never raise a KeyError. Any key that does not exist gets the value returned by the default factory.
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-8-07706fc5dc20> in <module>()
----> 1 d['one']
KeyError: 'one'
Can also initialize with default values:
namedtuple
The standard tuple uses numerical indexes to access its members, for example:
For simple use cases, this is usually enough. On the other hand, remembering which index should be used for each value can lead to errors, especially if the tuple has a lot of fields and is constructed far from where it is used. A namedtuple assigns names, as well as the numerical index, to each member.
Each kind of namedtuple is represented by its own class, created by using the namedtuple() factory function. The arguments are the name of the new class and a string containing the names of the elements.
You can basically think of namedtuples as a very quick way of creating a new object/class type with some attribute fields. For example:
We construct the namedtuple by first passing the object type name (Dog) and then passing a string with the variety of fields as a string with spaces between the field names. We can then call on the various attributes:
Conclusion
Hopefully you now see how incredibly useful the collections module is in Python and it should be your go-to module for a variety of common tasks!