Properly handling dicts where the keys are lambdas

Viewed 29

Imagine I want a dictionary that keeps polynomial basis functions as keys and returns their power as a value ( I could return values for more interesting things, but let's stick to this as an example).

d = {lambda x: x: 1, lambda x: x*x: 2}

This works and we can see that the lambdas are correct as in:

for func, power in d.items(): 
    print(f"{func(2)} is 2 to the {power} power")

# 2 is 2 to the 1 power
# 4 is 2 to the 2 power

Nonetheless, this doesn't work with more interesting examples, as in:

d = {lambda x: x**i: i for i in (1, 2)}

for func, power in d.items():
    print(f"{func(2)} is 2 to the {power} power")

#  4 is 2 to the 1 power
#  4 is 2 to the 2 power

So something is obviously off here, but I'm not getting any SyntaxError, so I don't understand why the lambdas are not being evaluated correctly. What gives?

Another issue I have is that I cannot access the keys directly. For example, this gives me a KeyError (not a SyntaxError!):

d[lambda x: x]

But this works:

key = list(d.keys())[0]
d[key]
# 1

My question pertains the use of lambdas as dict keys. Why do the lambdas not work properly if I define them in a loop (but work if I write them out)? And how would one access the keys without intermediate variables?

0 Answers
Related