1

I'm attempting to store a few methods on a dictionary using lambdas, but for some reason it's not giving the expected output. Moreover, I have no idea what would cause the output it IS giving.

valueDict = {
    1: (0, 5),
    7: (5, 10)
}

dothings = dict()
for key in valueDict:
    low, high = valueDict[key]
    print(f"Inserting randint({low}, {high}) into key {key}")
    dothings[key] = (lambda: randint(low, high))


print(f"Sample of key 1: {dothings[1]()}")

gives the following output:

Inserting randint(0, 5) into key 1
Inserting randint(5, 10) into key 7
Sample of key 1: 6

This is baffling to me- Since the print statements seem a good indicator that it's doing the correct inserts at the correct location- but then the output of calling a function of a specific key is wrong. I imagine this has something to do with my loop or my usage of lambdas, because the following code:

dothings = {
    1: lambda: randint(0, 5),
    7: lambda: randint(5, 10)
}
print(dothings[1]())

DOES correctly output a number in the range 0-5. I can't see the difference between these two methods of putting the lambdas into the dictionary however.

I'm primarily a Java programmer, so I'm wondering if this is some quirk of python / storing references to methods that I'm not aware of. Either way, big thanks to anyone that can help me out!

0 Answers0