Python defaultdic Tutorial

Python provides the dictionary structure in order to store key and value as a single item. It is very useful to store and query values according to their keys. By default, the dictionary returns KeyError when a non-existing key is provided. The defaultdict is an enhanced version of the dictionary where if a non-existing key and value are requested it they are created with default values and no error or exception is returned.

Import defaultdict

The defaultdic is not provided as a built-in dictionary. The defaultdict is provided via the collections module.

from collections import defaultdict

Alternatively, we can use long-form to call defaultdict.

import collections

collections.defaultdict

Create Default Function

The defaultdict requires a function which return value is used to return when a non-existing key and value is requested. The return value can be anything where the function name is specified to the defaultdict as a parameter.

from collections import defaultdict

def default_value():
   return "The key and value do not exist"

d = collections.defaultdict(default_value)

d[1]="ismail"

d[2]="ali"

print(d[1])

print(d[2])

print(d[3])
ismail
ali
The key and value do not exist

As we can see from the output the existing key and values are printed properly. But if the requested key does not exist the function default_value() is called and its return value is printed.

Leave a Comment