Joshua Merriman
Joshua Merriman

Reputation: 985

python - Simulating 'else' in dictionary switch statements

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?

Upvotes: 7

Views: 7040

Answers (5)

user2522252
user2522252

Reputation: 11

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')

Upvotes: 1

roj4s
roj4s

Reputation: 281

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.

Upvotes: 1

Michael Geary
Michael Geary

Reputation: 28850

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.

Upvotes: 2

Ryan O'Neill
Ryan O'Neill

Reputation: 3757

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!

Upvotes: 9

Óscar López
Óscar López

Reputation: 235994

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.

Upvotes: 7

Related Questions