Sep-07-2020, 03:07 PM
With thanks to all the contributers, i made an overview of
some alternatives for a switch or select case construction.
This includes the "case else" or "default" option.
Note that alt 1 is in fact a simple case of alt 2.
Note that alternative 3 requires a pip install.
Paul
some alternatives for a switch or select case construction.
This includes the "case else" or "default" option.
Note that alt 1 is in fact a simple case of alt 2.
Note that alternative 3 requires a pip install.
#the functions def AAA(): return 'AAA' def BBB(): return 'BBB' def ELSE(): return 'UNKNOWN' # --------------------------- #(1)single key dict with default def switcher1(k): myDict = {100:AAA(),200:BBB()} return myDict.get(k, ELSE()) print(switcher1(200)) print(switcher1(502)) # ----------------------------- #(2)tuple with (optional) multiple keys and default def switcher2(k): myDict2 = {('a'):AAA(), ('x', 'y', 'z'):BBB()} myDict2 = {key:value for item, value in myDict2.items() for key in item} return myDict2.get(k, ELSE()) print(switcher2('z')) print(switcher2('M')) # -------------------------------- #(3) range dict with default from range_key_dict import RangeKeyDict def switcher3(k): myDict3 = RangeKeyDict({(0,100): AAA(),(101,200): BBB()}) return myDict3.get(k, ELSE()) print(switcher3(152)) print(switcher3(5210))Can somebody write to PEP622 that they can save the time & effort.
![Cool Cool](https://python-forum.io/images/smilies/cool.png)
Paul
It is more important to do the right thing, than to do the thing right.(P.Drucker)
Better is the enemy of good. (Montesquieu) = French version for 'kiss'.
Better is the enemy of good. (Montesquieu) = French version for 'kiss'.