Search code examples
pythondefaultdict

Meaning of defaultdict(lambda: defaultdict(dict))


What is the meaning of the following line in Python?

x = defaultdict(lambda: defaultdict(dict))

Solution

  • Let's resolve it from the inside out. Firstly, dict is the dictionary type. Like other types, calling it creates an instance (also known as object) of that type. A defaultdict is a type that takes a callable parameter: something that, when called, produces an item to put in the dictionary. This happens when an entry is accessed that was not present, instead of producing a KeyError like an ordinary dict. Thirdly, lambda is a way to create unnamed functions based on a single expression, so these two are similar (the second holds a function that knows its own name, the first doesn't):

    y = lambda: defaultdict(dict)
    
    def y():
        return defaultdict(dict)
    

    And finally the whole thing is wrapped in another defaultdict. So the result is that x is a defaultdict that produces defaultdicts that produce dict instances. At the third level there aren't defaults anymore.