Using dictionaries for conditional execution instead of if..elif
data-structures, dictionary, if-statement, python
Solution
you could do :
v.get(value, case_generic)()
Problem
Say you have something like below: ``` def case_A(): print 'A' def case_B(): print 'B' def case_generic(): print 'some generic case' ``` And `value` is defined and has some value in it Do you see any scenario(s) where you wouldn't want to apply the pattern below: ``` v = {"A":case_A, "B":case_B} try: v[value]() except: case_generic() ``` instead of the standard: ``` if value == "A": case_A() elif value == "B": case_B() ...place n more if cases here... else: case_generic() ``` To me the first case looks way more compact and easy to manage, albeit with a slight increase in memory. Alternatively, do you see any ways of improving the above or using a better way alltogether?