Home >Backend Development >Python Tutorial >How Can I Access a Predefined List Based on a String Input in Python?
Accessing Variables by String Name
Problem:
You desire a function that returns a predefined list based on a string input. For instance, given a string "audio," the function should output the list ['mp3', 'wav'].
Easiest Solution with a Dictionary:
A standard dictionary can fulfill this requirement effortlessly.
get_ext = {'text': ['txt', 'doc'], 'audio': ['mp3', 'wav'], 'video': ['mp4', 'mkv'] } get_ext['video'] # Returns ['mp4', 'mkv']
Using Functions:
For more advanced applications, utilizing functions might be preferred.
Assigning a Dictionary's Get Method:
get_ext = get_ext.get get_ext('video') # Returns ['mp4', 'mkv']
Wrapping a Dictionary Inside a Function:
def get_ext(file_type): types = {'text': ['txt', 'doc'], 'audio': ['mp3', 'wav'], 'video': ['mp4', 'mkv'] } return types.get(file_type, [])
Creating a Custom Class for Extensibility:
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() get_ext('audio') # Returns ['mp3', 'wav']
This allows you to modify file types dynamically.
get_ext.types['binary'] = ['bin', 'exe'] get_ext('binary') # Returns ['bin', 'exe']
The above is the detailed content of How Can I Access a Predefined List Based on a String Input in Python?. For more information, please follow other related articles on the PHP Chinese website!