Home >Backend Development >Python Tutorial >How Can I Return a Predefined List in Python Based on String Input?
In Python, we sometimes encounter the need to return a specific list based on a provided string. This can be achieved using various methods, one of which involves leveraging dictionaries.
The most straightforward approach is to define a dictionary where keys represent the string inputs and corresponding values are the desired lists.
get_ext = {'text': ['txt', 'doc'], 'audio': ['mp3', 'wav'], 'video': ['mp4', 'mkv'] }
To retrieve the desired list, simply access the appropriate key:
get_ext['video'] # Output: ['mp4', 'mkv']
If prefer a function-based solution, you can assign the get method of the dictionary to a variable:
get_ext = get_ext.get
This function will return the list for the specified key or None if the key doesn't exist.
get_ext('video') # Output: ['mp4', 'mkv']
To specify a custom default value for unknown keys, consider using a wrapper function:
def get_ext(file_type): types = {'text': ['txt', 'doc'], 'audio': ['mp3', 'wav'], 'video': ['mp4', 'mkv'] } return types.get(file_type, [])
This function will return an empty list for unknown keys.
For performance-conscious applications, it's worth noting that the types dictionary in the wrapper function is recreated every time the function is called. To optimize this, you can create a class and initialize the types dictionary within the constructor, ensuring it's only created once.
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 class-based approach enables easy modification of the recognized file types while maintaining performance efficiency.
The above is the detailed content of How Can I Return a Predefined List in Python Based on String Input?. For more information, please follow other related articles on the PHP Chinese website!