Chris Clark Chris Clark - 6 months ago 29
Python Question

How does this Lambda Expression work?

I'm familiar with simple lambda expressions. However I have this lambda expression in a book.

dd_pair = defaultdict(lambda: [0,0])
dd_pair[2][1] = 1 #now dd_pair contains {2: [0,1]}


I didn't declare any input variables, which is not how I learned Lambdas.

The previous example from the book has

dd_dict = defaultdict(dict)
dd_dict["Joel"]["City"] = "Seattle"
#this produces {"Joel" : { "City": "Seattle"}}


This makes sense, The Key is
Joel
, the nested Key is
City
, and the value is
Seattle
.

My two part question is, how does a lambda work with no input variables? and should I assume that the
dd_pair[2][1]
is to create a key
2
and at index
1
of the list set the value
=1
?

Answer

lambda: [0, 0] is exactly the same as:

def zero_pair():
    return [0, 0]

that is, it is a function that takes no arguments and returns a len 2 array with the two entries set to 0. defaultdict takes a callable that takes no arguments and returns the value for a missing key so your second example (dd_pair = defaultdict(lambda: [0,0])) is the same as:

dd_pair = defaultdict(zero_pair)

Now, a dictionary in Python can take any value for its key (as long as they are hashable).

{0: 'integer', '0': 'string'}[0]  # 'integer'

So when we index into dd_pair with a two, since the dictionary doesn't have any key at 2 our lambda (which is equivalent to zero_pair) is called and returns a list with two zeros in it. We then set the second element in that list to 1, mutating the list in place.

So yes, you're pretty much spot on when you say:

should I assume that the dd_pair[2][1] is to create a key 2 and at index 1 of the list set the value = 1