What exactly does the lambda type do when used with defaultdict

I remember this example

from collections import defaultdict
d_int = defaultdict(int, a=10, b=12, c=13)
d_int.default_factory = lambda: 1
d_int['d']
1

When we pass an unknown key, it returns the default value instead of an error, I understand that. But in this SO question, filling out a nested dictionary becomes more complicated.

final = collections.defaultdict(lambda: collections.defaultdict(list))

What does the lambda type do in this case?

+4
source share
2 answers

This type of dictionary will be useful by default for two levels of data. Something like that:

{ k11 : { k21 : [...], k22 : [...] }, k12 : { ... } }

Every dictionary is here defaultdict.

lambdareturns defaultdictfor the second level when the key of the first level does not exist:

In [234]: final['k11'] # first level access
Out[234]: defaultdict(list, {})

In [235]: final['k11']['k21']  # second level access
Out[235]: []
+2
source

defaultdict need a function (factory).

collections.defaultdict(list). , , collections.defaultdict(list).

+2

Source: https://habr.com/ru/post/1683565/


All Articles