Difference between revisions of "Python Button Dictionary Case Statement"
Jump to navigation
Jump to search
Russ hensel (talk | contribs) |
Russ hensel (talk | contribs) (→How) |
||
Line 23: | Line 23: | ||
Assume we have build a dictionary something like | Assume we have build a dictionary something like | ||
− | case_dict = { "": | + | case_dict = { "one": sub_1, "2": sub_2, } |
+ | |||
+ | Then we can call the subroutine ( the switch case like statement ) | ||
+ | |||
+ | case_dict[ A ]() | ||
+ | |||
+ | It is really simple, supports very large number of cases, and is very fast. |
Revision as of 07:03, 13 April 2020
What/Why
There is a technique in Python to use a dictionary in place of a case statement ( which in any case Python does not have ). This is a cool technique that can both make code faster and easier to maintain. I have also found that it is particurlarly useful with Tkinter to build GUIs. This page will give a little introduction and link to some example code.
How
A Case Statement
A case or switch statement in other languages may look something like this:
( something like this, I just made it up ) switch on case A case "one" call sub_1() case "2" call sub_1() end switch
So when executed if A == "one" then sub_1 is called .......
Python Dict Approach
Assume we have build a dictionary something like
case_dict = { "one": sub_1, "2": sub_2, }
Then we can call the subroutine ( the switch case like statement )
case_dict[ A ]()
It is really simple, supports very large number of cases, and is very fast.