1

I have the following:

>>> {c: (lambda: c) for c in ["A","B"]}["A"]()
'B'

when I expect the result to be 'A'.

Note that

>>> {c: c for c in ["A","B"]}["A"]
'A'

Are lambdas not allowed in dictionary comprehensions or have I screwed up the syntax?

Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
Cramer
  • 1,785
  • 1
  • 12
  • 20
  • 2
    What do you mean by "not allowed"? There is a *surprising* value, but it is not an *error* – Caleth Jun 12 '18 at 08:44

1 Answers1

1

There's one object created by the lambda, and the value that it captures is modified during each element of the comprehension

It is the same as if you did

class Lambda:
    def set(self, value):
        self.value = value;
        return self
    def __call__(self):
        return value

lam = Lambda()
{c: lam.set(c) for c in ["A","B"]}["A"]()

Each entry in the dictionary has the same value, lam, that returns the last set value.

Caleth
  • 52,200
  • 2
  • 44
  • 75