I’m a ‘python neophyte’ and trying to grasp the inner workings of the dictionary datatype. Last night I was attempting to use one as a control structure (i.e. switch statement) for keyboard input on an openGL program.
The problem was that for some reason the dictionary kept evaluating ALL cases (two in this instance) instead of just the one from the key pressed.
Here is an example piece of code:
def keyboard(key):
values = {
110: discoMode(),
27: exit()
}
values.get(key, default)()
I spent an hour or more last night trying to find the answer to why every ‘case’ is evaluated, I’ve got a few ideas, but wasn’t able to clearly find the answer to the “why” question.
So, would someone be kind enough to explain to me why when I hit the ‘n’ key (the ascii representation is 110) that this piece of code evaluates the entry under 27 (the ESC key) too?
Apologize if this topic has been beaten to death but I looked and was unable to find the clear answer easily (maybe I missed it).
Thank you.
In this case, you are building a dict containing the return value of “discoMode()” assigned to 110, and the return value of “exit()” to 27.
What you meant to write was:
Which will assign 110 to the function discoMode (not call the function!), likewise for exit. Remember functions are first class objects: they can be assigned, stored, and called from other variables.