I know you can use a dictionary as an alternative to a switch statement such as the following:
def printMessage(mystring):
# Switch statement without a dictionary
if mystring == "helloworld":
print "say hello"
elif mystring == "byeworld":
print "say bye"
elif mystring == "goodafternoonworld":
print "good afternoon"
def printMessage(mystring):
# Dictionary equivalent of a switch statement
myDictionary = {"helloworld": "say hello",
"byeworld": "say bye",
"goodafternoonworld": "good afternoon"}
print myDictionary[mystring]
However if conditions are used, other than equality (==) which return true of false these cant be mapped as easily i.e.:
if i > 0.5:
print "greater than 0.5"
elif i == 5:
print "it is equal to 5"
elif i > 5 and i < 6:
print "somewhere between 5 and 6"
The above cannot be directly converted to a dictionary key-value pair as is:
# this does not work
mydictionary = { i > 0.5: "greater than 0.5" }
A lambda can be used since it is hash-able but the only way to get the resulting string out of the map is by passing the same lambda object into the dictionary and not when the evaluation of the lambda is true:
x = lambda i: i > 0.5
mydictionary[x] = "greater than 0.5"
# you can get the string by doing this:
mydictionary[x]
# which doesnt result in the evaluation of x
# however a lambda is a hashable item in a dictionary
mydictionary = {lambda i: i > 0.5: "greater than 0.5"}
Does anyone know of a technique or method to create a mapping between a lambda evaluation and a return value? (this maybe similar to pattern matching in functional language)
Your conditions are sequential in nature; you want to test one after the other, not map a small number of keys to a value here. Changing the order of the conditions could alter the outcome; a value of
5
results in"greater than 0.5"
in your sample, not"it is equal to 5"
.Use a list of tuples:
after which you can access each one in turn until one matches:
Re-ordering the tests will change the outcome.
A dictionary works for your first example because there is a simple equality test against multiple static values that is optimised by a dictionary, but there are no such simple equalities available here.
You can't use a dictionary to map arbitrary conditionals since more than one of them could be true at the same time. Instead you need to evaluate each one sequentially and execute the associated code the first time a true one is encountered. Here's an outline of one way to formally implement something like that which even allows the equivalent of a
default:
case.Output:
Not directly related, but I often use a paradigm similar to the example below for replacing cascading ifs with a dictionaruy lookup.