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


Solution 1:[1]

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'

Solution 2:[2]

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

Solution 3:[3]

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)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 BrokenBenchmark
Solution 2 FLAK-ZOSO
Solution 3 Dharman