7

I'm working on a project which used a load of If, Elif, Elif, ...Else structures, which I later changed for switch-like statements, as shown here and here.

How would I go about adding a general "Hey, that option doesn't exist" case similar to an Else in an If, Elif, Else statement - something that gets executed if none of the Ifs or Elifs get to run?

Joshua Merriman
  • 925
  • 1
  • 8
  • 13

5 Answers5

9

If the else is really not an exceptional situation, would it not be better to use the optional parameter for get?

>>> choices = {1:'one', 2:'two'}
>>> print choices.get(n, 'too big!')

>>> n = 1
>>> print choices.get(n, 'too big!')
one

>>> n = 5
>>> print choices.get(n, 'too big!')
too big!
Ryan O'Neill
  • 3,727
  • 22
  • 27
7

You could catch the KeyError error that ensues when a value is not found in the map, and return or process there a default value. For example, with n = 3 this piece of code:

if n == 1:
    print 'one'
elif n == 2:
    print 'two'
else:
    print 'too big!'

Becomes this:

choices = {1:'one', 2:'two'}
try:
    print choices[n]
except KeyError:
    print 'too big!'

Either way, 'too big!' gets printed on the console.

Óscar López
  • 232,561
  • 37
  • 312
  • 386
2

The first article you linked to had a very clean solution:

response_map = {
    "this": do_this_with,
    "that": do_that_with,
    "huh": duh
}
response_map.get( response, prevent_horrible_crash )( data )

This will call prevent_horrible_crash if response is not one of the three choices listed in response_map.

Michael Geary
  • 28,450
  • 9
  • 65
  • 75
1

Let's say you have a function f(a,b) and different setups of parameters according to the value of some variable x. So you want to execute f with a=1 and b=3 if x='Monday' and if x='Saturday' you want to execute f with a=5 and b=9. Otherwise you will print that such value of x is not supported.

I would do

from functools import partial
def f(a,b):
 print("A is %s and B is %s" % (a,b))

def main(x):
 switcher = {
             "Monday": partial(f,a=1, b=3),
             "Saturday": partial(f, a=5, b=9)
            }
 if x not in switcher.keys():
  print("X value not supported")
  return

 switcher[x]()

this way f is not executed on declaration of switcher but at the last line.

roj4s
  • 251
  • 2
  • 8
1

Some one-line alternatives:

choices = {1:'one', 2:'two'}
key = 3

# returns the provided default value if the key is not in the dictionary
print(choices[key] if key in choices else 'default_value')

# or using the dictionary get() method
print(choices.get(key, 'default_value')