Suppose I have a list of string ['a', 'b', 'c']
. I want to generate one dictionary with the element in that list ('a'
, 'b'
and 'c'
) as key, and a function which prints the key as the value (print('a')
, print('b')
, print('c')
).
I tried this code:
l = ['a', 'b', 'c']
m = {k: (lambda: print(k)) for k in l}
But the result is not right:
m['a']()
c
m['b']()
c
If I call the functions directly, like m = {k: print(k) for k in l}
, the output is correct (although the dictionary does not store the right values).
Why doesn't it work with the lambda
s?