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.