Make your own defaultdict

Posted by Afsal on 21-Oct-2022

Hi Pythonistas!

Today we will learn how defaultdict works internally by making our defaultdict. We know that defaultdict is a very useful datatype from the collections module. 

Code

from collections import defaultdict
a = defaultdict(lambda: "hello")
a["a"] = 1
a["b"] = 2

print(a["a"])
print(a["b"])
print(a["c"])

Output

1
2
hello

Here the key is c was not present in the defaultdict but when we access it won't raise a KeyError

Now we will create our own default dict. In a previous post about operator overloading. We have mentioned python's behavior is controlled by the dunder/magic methods. There is a dunder method called __missing__ this is triggered when we access dictionary using key. Let us check with an example

Code

class ExtendedDict(dict):

    def __init__(self, **kwargs):
        default = kwargs.pop("default")
        super().__init__(kwargs)
        if default:
            self.default = default

    def __missing__(self, key):
        if self.get(key):
            return self.get(key)
        return self.default

a = ExtendedDict(a=1, b=2, default="hello")
print(a)
print(a["a"])
print(a["c"])

Output

{'a': 1, 'b': 2}
1
hello 

Here in this example, we are overriding the __missing__ method and returning a default value. So we created our own defaultdict

Hope you have learned something from this post. Please share your feedback with afsal@parseltongue.co.in