0

I have this script that sets up multiple different defaultdict's within an ordinary dictionary. However, the default values appear to be incorrect after setup. I would like to verify that this is indeed a bug:

from collections import defaultdict

labels = {1: 0, 2: 1, 3: 2, 4: 9000}
my_dict = {}

for label, value in labels.items():
    my_dict[label] = defaultdict(lambda: value)

    for tdx in range(2):
      my_dict[label][tdx] = -1

line = "Bug at my_dict[1][-1]: {}".format(my_dict[1][-1])
print(line) # Prints 9000
Josh
  • 2,232
  • 3
  • 15
  • 33
  • My bad, i forgot lambdas have a scope. Both my comments were wrong so I've deleted them. – wjandrea Apr 23 '20 at 02:17
  • 1
    To solve this you can write the lambda as `lambda result=value: result`. The defaults of parameters are evaluated once on function/lambda creation. – Michael Butscher Apr 23 '20 at 02:26
  • I like your solution @Michael Butscher! I wish this question wasn't immediately closed. I think that would be valuable knowledge to share. – Josh Apr 23 '20 at 02:47
  • 1
    @Josh this is a very well known gocha, and Michael's solution is very well known too - there must be dozens of duplicates on SO alone. – bruno desthuilliers Apr 23 '20 at 06:29
  • @bruno desthuilliers It was not known to me and was not available after many queries in Stackoverflow. The "duplicated case" does not even provide a solution like Michael's. – Josh Apr 24 '20 at 16:36

0 Answers0