0

I was doing a complicated aggregation in pandas and found an unusual issue in Python dictionaries.

When I do:

g = {
    "grade": dict(
        ["is_" + val, (lambda x: val)]
        for val in ['A', 'B', 'C', 'D', 'E', 'F']
    )
}

I was expecting I would get multiple functions: g['grade']['is_A'], g['grade']['is_B'], g['grade']['is_C'], ... each of which will give back A, B, C, ... respectively.

The thing is they all give me return the value F (the last item in the iterator)

In []: g['grade']['is_A'](1)
Out[]: 'F'

In []: g['grade']['is_B'](1)
Out[]: 'F'

In []: g['grade']['is_C'](1)
Out[]: 'F'

...

In []: g['grade']['is_F'](1)
Out[]: 'F'

Even doing lambda without the argument gives the same value. I am assuming this is happening because when I run the lambda, it is looking for the variable val and finding that the val refers to 'F' in the last iteration.

Is there any way for me to use the actual value in a dictionary generator ?

I basically want to create like 300-400 functions for is_VALUE where the values are dynamically being fetched from another place.

Cœur
  • 37,241
  • 25
  • 195
  • 267
AbdealiLoKo
  • 3,261
  • 2
  • 20
  • 36
  • 1
    Short answer: the variable inside a lambda function is evaluated when executing but not creating. – Sraw May 23 '18 at 08:06
  • You can fix that with `lambda x, val=val: val`. But why do you even _want_ a function that ignores its arg and returns a constant? Surely there's a more efficient way to do what you're trying to do – PM 2Ring May 23 '18 at 08:11
  • yeah, this was a stripped down example - the arg is used along with the `val` in the actual function. – AbdealiLoKo May 23 '18 at 10:04

0 Answers0