Home > Back-end >  Using a Python dictionary to simulate switch statement with default case
Using a Python dictionary to simulate switch statement with default case

Time:04-01

Is there a valid Python syntax for the following idea:

d = {_: 'value for any other key', 'x': 'value only for x key'}
value = d[key]

which should assign 'value only for x key' value ONLY when key='x'?

I have the following structure in my code, but I want to replace it with something that looks like the statements above.

if key == 'x':
  value = 'value only for x key'
else:
  value = 'value for any other key'

CodePudding user response:

I would recommend using a defaultdict from the collections module, as it avoids the need to check for membership in the dictionary using if/else or try/except:

from collections import defaultdict

d = defaultdict(lambda: 'value for any other key', {'x': 'value only for x key'})

item = 'x'
value = d[item]
print(value) # Prints 'value only for x key'

item = 'y'
value = d[item]
print(value) # Prints 'value for any other key'

CodePudding user response:

Python has match statement which is the equivalent to the C's switch statement since version 3.10, but your method may be used too:

dictionary = {
    'a': my_a_value,
    'b': my_b_value,
    '_': my_default_value
}
try:
    x = dictionary[input()]
except KeyError:
    x = dictionary['_']

CodePudding user response:

You can use dictionary's get function to customize the return value:

d = {
    'x' : 'value only for x key', 
    'y' : 'value only for y key',
    '_' : 'value for any other key'
}

key = input("Enter the key")

value = d.get(key, d['_'])

print("Value is ", value)
  • Related