1

I want to make multiple lambda functions with different parameters and bind them to a dictionary.

dic_funcs = {}

dates = ['2018', '2019', '2020']

idx = ['0', '1', '2']

def printt(text):
    print(text)


for d in dates:
    for i in idx:

        #print(d, i)

        dic_funcs[d + '_' + i] = lambda:printt(d + '_' + i)


for key, item in dic_funcs.items():
    print(key)
    item()      
    print('-----')  

I thought that each key and the result of the corresponding value(lambda function) would be the same, but they are not.

2018_0
2020_2
-----
2018_1
2020_2
-----
2018_2
2020_2
-----
2019_0
2020_2
-----
2019_1
2020_2
-----
2019_2
2020_2
-----
2020_0
2020_2
-----
2020_1
2020_2
-----
2020_2
2020_2
-----

I think I bound the same date and index number each time. What could be the problem? I'd appreciate it if I could get some help with it.

maynull
  • 1,936
  • 4
  • 26
  • 46

1 Answers1

1

In your lambda expression you've got an i which is from your loop through idx, and a d which is from your loop through dates. The both these values in your lambda expression aren't evaluated at function definition but rather when the function is called, so each time you're doing print(d + '_' + i), the function just looks up the current value of d and i, which is just the value of the last thing in for d in dates and for i in idx, which is why you're getting the same value each time.

You can work around this with a hack like:

dic_funcs[d + '_' + i] = lambda a=i, b=d:printt(b + '_' + a)

Which gives you your intended behavior

Primusa
  • 13,136
  • 3
  • 33
  • 53