s98i5w
Last Updated: February 25, 2016
·
955
· lyndsysimon

Pythonic "Switch...Case"

Python can emulate the switch...case flow control structure found in many languages. All you need to do is put your expected values as keys for a dictionary.

def starts_with_s():
    return ' '.join(['No','soup','for','you!']).upper()

words = {
    'a': lambda: 'Apple',
    'b': lambda: 'Blueberry',
    'c': lambda: 'Cookie',
    's': starts_with_s
}

print words['a']()
>>> 'Apple'
print words['b']()
>>> 'Blueberry'
print words['c']()
>>> 'Cookie'
print words['s']()
>>> 'NO SOUP FOR YOU!'

The lambdas are necessary only if you're doing more than merely returning a string - since they're defined functions, they're passed back and executed just like the named function starts_with_s().

Default values are best handled as an exception:

try:
    print words['x']
except KeyError:
    print 'I don\'t know anything about that...'
>>> 'I don't know anything about that...'

Finally, this structure is able to use any immutable object as a key. This can come in handy:

from random import choice

domain = 'rps'

winner = {
    ('r','r'): 'Tied. Rock on!',
    ('p','p'): 'Draw. Get it? Draw!? :)',
    ('s','s'): 'Tied. Cut that out!',
    ('r','p'): 'You lose. Paper covers rock',
    ('r','s'): 'You win. Rock breaks scissors',
    ('p','r'): 'You win. Paper covers rock',
    ('p','s'): 'You lose. Scissors cut paper',
    ('s','r'): 'You loss. Rock breaks scissors.',
    ('s','p'): 'You win. Scissors cut paper'
}

for idx in range(10):
    user, computer = choice(domain), choice(domain)
    print 'Trial %s: %s' % (idx+1, winner[(user, computer)])

>>> Trial 1: You lose. Paper covers rock
>>> Trial 2: You win. Scissors cut paper
>>> Trial 3: You win. Scissors cut paper
>>> Trial 4: Tied. Cut that out!
>>> Trial 5: You win. Paper covers rock
>>> Trial 6: You win. Scissors cut paper
>>> Trial 7: You win. Paper covers rock
>>> Trial 8: You lose. Scissors cut paper
>>> Trial 9: You loss. Rock breaks scissors.
>>> Trial 10: Tied. Cut that out!

Let's see you do that in PHP!

3 Responses
Add your response

9429

You can also use a function as a switch.

def buildingtype(x):
    return {
        'Low-rise': 'LR',
        'High-rise': 'HR',
        'Mid-rise': 'MR',
        'Townhouse': 'TH',
        'Loft': 'LO'
        }.get(x, '')   # Default
over 1 year ago ·
9432

I've been using the literal notation like that more often these days, but using .get() to provide a default value is slick, and something that I've not had a need for yet.

over 1 year ago ·
17807

How do you see my version of pythonic switch:
https://github.com/mysz/py-simpleswitch

? :)

over 1 year ago ·