Python - Simulate switch statement

Introduction

Because dictionaries and lists can be built at runtime dynamically, they are sometimes more flexible than hardcoded if logic:

Demo

choice = 'ham' 
print({'test':  1.25,         # A dictionary-based 'switch' 
       'ham':   1.99,         # Use has_key or get for default 
       'eggs':  0.99, 
       'bacon': 1.10}[choice])

Result

The equivalent if statement

Demo

choice = 'ham' 
if choice == 'test':          
    print(1.25) # from  w  w  w  .  j a v a  2 s  .c  om
elif choice == 'ham': 
    print(1.99) 
elif choice == 'eggs': 
    print(0.99) 
elif choice == 'bacon': 
    print(1.10) 
else: 
    print('Bad choice')

Result

Related Topic