I want to have a collection of anonymous functions that will update the associated value in a dictionary but when i call the anonymous function it updates only the last value in the dictionary.
Here's the code:
def add2(dic, key):
dic[key] += 2
dic = {1:0, 2:0, 3:0}
acts = {}
for key in dic:
acts[key] = lambda: add2(dic, key)
Executing one of the lambda will result in this:
>>> acts[1]()
>>> dic
{1:0, 2:0, 3:2}
The same will happen if i execute associated with key 2, it will always update the last element in the dictionary.
I am wandering why this happens.
I suppose that is due to the fact that the value that gets into the add2 function refers to the same value in memory. You may need to specify them explicitly.
example:
acts[key] = lambda x=key, y=dic: add2(dic=y, key=x)