I'm trying to create functions inside of a loop and storing them in a dictionary. The problem is that all entries in the dictionary seem end up mapping to the last created function. The code goes like this:
d = {}
def test(**kwargs):
for k in kwargs:
def f():
print k, kwargs[k]
d[k] = f
f()
test(foo=1, bar=2)
print 'should print the same output as before'
d['foo']()
d['bar']()
This outputs:
foo 1
bar 2
should print the same output as before
bar 2
bar 2
Any idea why?