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.