Why do you need a lambda for the defaultdict socket?

I'm a bit confused about why you need lambda function to embed defaultdict

Why can't you do it like this?

test = defaultdict(defaultdict(list)) 

instead

 test = defaultdict(lambda:defaultdict(float)) 
+6
source share
1 answer
 test = defaultdict(defaultdict(list)) 

Because defaultdict requires you to give it something that you can call to create keys for missing values. list is so callable, but defaultdict(list) not. This is an instance of defaultdict , and you cannot call defaultdict .

lambda is a function that, when called, returns a value that can be used in the dictionary, so it works.

Essentially, defaultdict(list) will be evaluated before the defaultdict instance is defaultdict , and you want to defer it until a missing key is found. This is why the called object (type or function) is used here.

+7
source

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


All Articles