I am trying to understand some code and I found the following script:
defaultdict(lambda: defaultdict(lambda: 0))
I am not familiar with defaultdict neither with lambda function. I suspect that this is equivalent to initialize a dictionary which values are also a dictionary. Am I wright?
A lambda
expression defines a function in-place. Arguments go before the :
, and the result of the function goes after it. For example:
>>> inc = lambda x: x+1
>>> inc(3)
4
>>> add = lambda x, y: x + y
>>> add(19, 23)
42
>>> zero = lambda: 0
>>> zero()
0
defaultdict
is a dict
that creates a default value any time you access it with a non-existent key. It does this by calling the function you pass to it. A common use case is to create a counter by having a defaultdict that automatically creates zero values that can then be incremented:
>>> foo = defaultdict(lambda: 0)
>>> foo["bar"]
0
>>> foo["bar"] += 1
>>> foo["bar"]
1
Since the function used by a defaultdict
can be anything, we can nest them by giving an outer dict a function that returns an inner defaultdict
:
>>> foo = defaultdict(lambda: defaultdict(lambda: 0))
>>> foo["bar"]["baz"]
0