Python Button Dictionary Case Statement

From OpenCircuits
Jump to navigation Jump to search

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   = { "": sub1,  "": sub2,  }