2

I have some lamdba functions as values in a dictionary. I would like to create new dictionary from the existing one that has lambdas derived from the values in the first. However, I am getting weird pointer behavior when I do this: all the composed lambda functions in the second dictionary point to its last entry.

base_checks = {'big': lambda x: x > 10, 'small': lambda x: x < 0.01}
fancy_checks = {name: lambda x: base_checks[name](x) for name in ['big', 'small']}

I wrote some example code above to describe this behavior. The function fancy_checks['big'] is supposed to point to base_checks['big'] but it actually points to the function base_checks['small'].

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Charles F
  • 539
  • 6
  • 11
  • I don't know about your real code, but you don't need to create new functions in your example. You can just use the functions from the original dict as the values of the new dict too. – user2357112 May 04 '18 at 03:38
  • @user2357112 of course I realize that.... in the real code the lamdas in the second dictionary are very complicated. – Charles F May 04 '18 at 03:55

0 Answers0