2

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?

moooeeeep
  • 31,622
  • 22
  • 98
  • 187
Fei Gao
  • 135
  • 2

2 Answers2

4

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
Dan D.
  • 73,243
  • 15
  • 104
  • 123
0

Just an alternative method to see things more logically.
d=dict((str(i),lambda v, i=i: v==i ) for i in range(3))

this will give the same results as above

fazkan
  • 352
  • 3
  • 11