Skip to Content
Secret Recipes of the Python Ninja
book

Secret Recipes of the Python Ninja

by Cody Jackson
May 2018
Intermediate to advanced content levelIntermediate to advanced
380 pages
9h 37m
English
Packt Publishing
Content preview from Secret Recipes of the Python Ninja

Implementing defaultdict

Another dictionary subclass, defaultdict calls a factory function to provide missing values; basically, it creates any items that you try to access, but only if they don't currently exist. This way, you don't get KeyError when trying to access a non-existent key.

All the standard dictionary methods are available, as well as the following:

  • __missing__(key): This method is used by the dict class __getitem__() method when the requested key is not found. Whatever key it returns (or an exception if no key is present) is passed to __getitem__(), which processes it accordingly.

    Assuming the default_factory is not None, this method calls the factory to receive a default value for key, which is then placed in the dictionary ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

The Expanding World of Python

The Expanding World of Python

Dane Hillard

Publisher Resources

ISBN: 9781788294874Supplemental Content