0

Hi this puzzeles me for a while now:

I want to add to an existing dictionary a new key with a specific function (myfun) but using different parameters for the same function:

dct = {}
params = {'a':[10,20],'b':[-10,10]}
def myfun(x,y):
    return (x+y)
print(myfun(*params['a'])) #desired output for dct['a'](1,1) = 30
print(myfun(*params['b'])) #desired output for dct['b'](1,1) = 0

for key in params.keys():
    dct[key]=lambda x,y: myfun(params[key][0]*x,params[key][1]*y)
    
print(dct['a'](1,1)) # should be 30
print(dct['b'](1,1)) # should be 0 

but apparently it keeps only the last key (in this case 'b').

Any ideas?

1 Answers1

0

Thanks @Chris:

use lambda-parameters initialized:

dct[key]=lambda x,y,xx=params[key][0],yy=params[key][1]: myfun(xx*x,yy*y)

this resolved my question!