Home >Backend Development >Python Tutorial >How Can I Select Variables in Python Using a String Input?
To select a variable based on a string input, there are several viable approaches.
Dictionary
An ordinary dictionary is often suitable for this task:
get_ext = {'text': ['txt', 'doc'], 'audio': ['mp3', 'wav'], 'video': ['mp4', 'mkv']} get_ext['video'] # returns ['mp4', 'mkv']
Function
If a function is required for specific reasons, you can assign to the get method of the dictionary:
get_ext = get_ext.get # Equivalent to get_ext = lambda key: get_ext.get(key) get_ext('video') # returns ['mp4', 'mkv']
This will return None for unknown keys by default. To raise a KeyError instead, assign to get_ext.__getitem__:
get_ext = get_ext.__getitem__ # Equivalent to get_ext = lambda key: get_ext.__getitem__(key) get_ext('video') # returns ['mp4', 'mkv']
Custom Default Value
You can implement a custom default value by wrapping the dictionary in a function:
def get_ext(file_type): types = {'text': ['txt', 'doc'], 'audio': ['mp3', 'wav'], 'video': ['mp4', 'mkv']} return types.get(file_type, [])
Optimizing
To avoid recreating the dictionary on every function call, you can use a class:
class get_ext(object): def __init__(self): self.types = {'text': ['txt', 'doc'], 'audio': ['mp3', 'wav'], 'video': ['mp4', 'mkv']} def __call__(self, file_type): return self.types.get(file_type, []) get_ext = get_ext()
This allows for easy modification of recognized file types:
get_ext.types['binary'] = ['bin', 'exe'] get_ext('binary') # returns ['bin', 'exe']
The above is the detailed content of How Can I Select Variables in Python Using a String Input?. For more information, please follow other related articles on the PHP Chinese website!