Python defaultdict and lambda

后端 未结 5 626
野的像风
野的像风 2020-12-02 05:31

In someone else\'s code I read the following two lines:

x = defaultdict(lambda: 0)
y = defaultdict(lambda: defaultdict(lambda: 0))

As the a

5条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-02 06:27

    defaultdict takes a zero-argument callable to its constructor, which is called when the key is not found, as you correctly explained.

    lambda: 0 will of course always return zero, but the preferred method to do that is defaultdict(int), which will do the same thing.

    As for the second part, the author would like to create a new defaultdict(int), or a nested dictionary, whenever a key is not found in the top-level dictionary.

提交回复
热议问题