Python Defaultdict Example

The python defaultdict class is a subclass of dict class, it supports all the functions that dict class provides. But when you provide a key that does not exist in the python dict object, the dict object will return a KeyError.

But the defaultdict object provides a default_factory attribute which is a python function and when this circumstance happened to the defaultdict object it will use this function to generate a value for the unexisting key and it will throw any error. Now let us see some examples.

1. How To Create A Python defaultdict Object.

  1. Before you can use the python defaultdict class, you should import it from the python collections package.
  2. Then you can create a python defaultdict object by the defaultdict class constructor function and pass a default_factory function as the parameter.
  3. For example defaultdict(list) will create a python defaultdict object and pass the list function as the default_factory function, so all the unexisting key’s value will be a list object. Let us look at the below example.
    Python 3.8.5 (default, Aug  5 2020, 09:44:06) [MSC v.1916 64 bit (AMD64)] :: Anaconda, Inc. on win32
    Type "help", "copyright", "credits" or "license" for more information.
    # import the defaultdict class from the python collections package.
    >>> from collections import defaultdict
    # create a defaultdict object and pass list function as the parameter.
    >>> dict_1 = defaultdict(list)
    # the key 'python' does not exist in the defaultdict object, then it will return an empty list object created by the default_factory function.
    >>> print(dict_1['python'])
    # this defaultdict default_factory function is a dict class.
    >>> dict_2 = defaultdict(dict)
    # then for unexisting key, it will create an empty dict object as the value.
    >>> print(dict_2['python'])
    # you can also create a custom python function and use this function as the defaultdict object's default_factory function.
    >>> def default_func():
            # this function just return a dict object.
    ...     return {'default_object','default_object'}
    # use the above customized python function as the defaultdict object default_factory function.
    >>> dict_3 = defaultdict(default_func)
    >>> print(dict_3['python'])

2. Python defaultdict VS dict Examples.

  1. Open a terminal and go to the Python interactive console.
  2. Input the below command that uses the python dict object in the python console, and you will get the KeyError error.
    >>> dict_1 = {}
    # because the key 'python' does not exist in the dict object dict_1, so it will throw the KeyError error.
    >>> print(dict_1['python'])
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    KeyError: 'python'
  3. Now we can run the below command to create a python defaultdict object, and for the unexisting key the defaultdict object will return an integer value.
    # first import the defaultdict class from the collections package.
    >>> from collections import defaultdict
    # pass int function as the default_factory function to the defaultdict constructor function.
    >>> dict_2 = defaultdict(int)
    # the 'python' key does not exist in the defaultdict object, so it will return a default value (0) created by the int function.
    >>> print(dict_2['python'])

1 thought on “Python Defaultdict Example”

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.