Gene Xu
Gene Xu

Reputation: 649

defaultdict lambda with two arguments (it's not argument per se for lack of word)

Hi I'm new to python defaultdict and it's callable argument. I have the following mocked code. Can someone help me to understand it?

a = 1.0
d = defaultdict(
        lambda: a,
        [(w, i) for w, i in dict_foo.items()])

What would d look like if d[key] when the key doesn't exist?

Upvotes: 1

Views: 221

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476557

The part after the comma (,) is not part of the lambda-expression, these are elements that are treated like these would as if you had constructed a dict. Like described in the documentation:

Returns a new dictionary-like object. defaultdict is a subclass of the built-in dict class. It overrides one method and adds one writable instance variable. The remaining functionality is the same as for the dict class and is not documented here.

Now a dict can take as parameter an iterable of 2-tuples, and it then will add these as key-value pairs.

So the above is, more or less, equivalent to:

d = defaultdict(lambda: a)
for w, i in dict_foo.items():
    d[w] = i

Given dict_foo is a dictionary, it is probably more elegant to write:

d = defaultdict(lambda: a, dict_foo)

We here thus construct a defaultdict with as key-value pairs the items in dict_foo, and we use lambda: a as a "factory" to construct values for missing keys.

Upvotes: 3

Related Questions