I need to define a dictionary of python lambda functions through a for cycle. Each lambda function needs the value of the relative dictionary key to work, but my hope is to avoid to pass such key as an argument. Here is a dummy version of my problem.
Given
a = {'bar': 0, 'foo': 1} # a reference dictionary
dic1 = {'bar': lambda x: x['bar'], 'foo': lambda x: x['foo']}
dic2 = {key: lambda x: x[key] for key in a}
I expect dic1 and dic2 to do the same thing, however only dic1 behaves as I would want to. In particular, the result of
print(dic1['bar'](a), dic1['foo'](a))
print(dic2['bar'](a), dic2['foo'](a))
is
0 1
1 1
instead of
0 1
0 1