python - Expressions in a dictionary mapping -
i have series of conditionals of form:
if ':' in particle: elif 'eq' in particle: else elif 'lt' in particle: thing elif 'le' in particle: etc. elif 'gt' in particle: etc., etc. elif 'ge' in particle: etc., etc., etc. elif 'ne' in particle: more etc.
i want implement using dictionary mapping pattern, having issues keys.
i tried this:
def case_evaluator(particle): switcher = { ':' in particle: something, 'eq' in particle: else, 'lt' in particle: thing, ... } return switcher.get(particle, "nothing")
but, kept getting "nothing." how can give nothing?
this seems should simple, alas...
you want have dictionary maps characters functions.
char_function_dict = { ':': colon_function, 'eq': eq_function, 'lt': lt_function # ...and on... }
then, can iterate on key-value pairs in dictionary.
def apply_function(particle): char, function in char_function_dict.items(): if char in particle: function()
however, note structure doesn't use specific dictionaries , doesn't preserve order characters checked. perhaps more simple use list of 2-element tuples.
char_functions = [ (':', colon_function), ('eq', eq_function), ('lt', lt_function) # ...and on... ] def apply_function(particle): char, function in char_functions: if char in particle: function() break # successive functions not run
setting either of these structures allow arguments and/or keyword arguments passed functions easy:
def apply_function(particle, *args, **kwargs): char, function in char_functions: if char in particle: function(*args, **kwargs) break
Comments
Post a Comment