Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do you need lambda to nest defaultdict?

I am a bit confused on why you need a lambda function for nesting defaultdict

Why can't you do it like this?

test = defaultdict(defaultdict(list))

instead of

test = defaultdict(lambda:defaultdict(float))
like image 530
Kevin Avatar asked Jun 03 '15 01:06

Kevin


1 Answers

test = defaultdict(defaultdict(list))

Because defaultdict requires that you give it something that can be called to create keys for missing values. list is such a callable, but defaultdict(list) is not. It's a defaultdict instance, and you can't call a defaultdict.

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

Essentially, defaultdict(list) is going to be evaluated before your defaultdict is instantiated, and you want to defer that until a missing key is encountered. This is why a callable object (a type or a function) is used here.

like image 143
kindall Avatar answered Oct 04 '22 00:10

kindall