0

I'm trying to make a list of defaultdicts, each with their own unique lambda. This works perfectly fine if I do the indexing by hand, eg

lambda_dictlist.append(defaultdict(lambda: default_values[0], original_dictlist[0]))
lambda_dictlist.append(defaultdict(lambda: default_value[1], original_dictlist[1]))
etc...

However, once I put this in a forloop as follows:

for i in range(len(original_dictlist)):
    lambda_dictlist.append(defaultdict(lambda: default_values[i], original_dictlist[i]))

each iteration, the newest default value overwrites the original default values. This overwrite is to the level of the actual id, as the id of the lambda changes from the original value to the id to the id of the most recent lambda.

Mara
  • 1
  • 1
    What do you mean by "the newest default value overwrites the original default values"? What output do you get that supports this conclusion? What is `default_values` and `original_dictlist`? Please show a [mcve] with output. – Code-Apprentice Nov 25 '21 at 16:03
  • While the link Sayandip Dutta gives explains why the example works the way it does, capturing `i` with a default is probably not the best solution. Instead, you can loop over your lists directly with `for default, original = zip(default_values, original_dictlist)`. – Code-Apprentice Nov 25 '21 at 16:06
  • This seems a little like an xy problem. It would be interesting to know the use case for this because there’s probably a pythonic approach to the underlying problem that doesn’t involve a list of lambdas. – Mark Nov 25 '21 at 16:13

0 Answers0