简体   繁体   中英

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'

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'

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM