I'm creating a one liner to map the string of int to a function testing if the values are matched. Ideally, the result dictionary d
behaves like d['0'](0) is True
and d['0'](1) is False
. But instead, I get the following output:
>>> d = { str(i): lambda v: v == i for i in range(3) }
>>> d['0'](0)
False
>>> d['0'](2)
True
I'm guessing the reason being lazy evaluation. I guess I could build the dictionary with a for
loop correctly but I want a one line expression instead.
Can anyone explain why this approach fails and how I do it right?
You need to capture the current value of i
for each lambda which can be done via the default argument i=i
. See:
>>> d = { str(i): lambda v, i=i: v == i for i in range(3) }
>>> d['0'](0)
True
>>> d['0'](2)
False