CoderX
CoderX

Reputation: 162

Using a Python dictionary to simulate switch statement with default case

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'

Upvotes: 1

Views: 1221

Answers (3)

Rishabh
Rishabh

Reputation: 902

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)

Upvotes: 0

BrokenBenchmark
BrokenBenchmark

Reputation: 19223

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'

Upvotes: 3

FLAK-ZOSO
FLAK-ZOSO

Reputation: 4088

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['_']

Upvotes: 0

Related Questions