Home >Backend Development >Python Tutorial >How Can I Access Variable Values Using Their String Names in Python?

How Can I Access Variable Values Using Their String Names in Python?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-11 11:54:11750browse

How Can I Access Variable Values Using Their String Names in Python?

Accessing Variable Values by String Name

For many scenarios, the string-based variable lookup can be achieved using dictionaries. Here's how:

get_ext = {'text': ['txt', 'doc'],
           'audio': ['mp3', 'wav'],
           'video': ['mp4', 'mkv']}

Now, you can retrieve the desired list by the string input:

get_ext['audio']  # ['mp3', 'wav']

If you prefer using a function, you can assign the get method of the dictionary or its item fetching method (__getitem__) to it:

get_ext = get_ext.get
get_ext('video')  # ['mp4', 'mkv']

Assigning to get_ext.get provides a default behavior of returning None for unknown keys. For a KeyError instead, assign to get_ext.__getitem__.

Alternatively, you can wrap the dictionary inside a function to provide a custom default value:

def get_ext(file_type):
    types = {'text': ['txt', 'doc'],
             'audio': ['mp3', 'wav'],
             'video': ['mp4', 'mkv']}
    return types.get(file_type, [])

To optimize the setup, you can define a class with a call method to handle the lookup:

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, [])

This approach improves efficiency by creating the types dictionary only once and allows for dynamic updates:

get_ext = get_ext()
get_ext.types['binary'] = ['bin', 'exe']
get_ext('binary')  # ['bin', 'exe']

The above is the detailed content of How Can I Access Variable Values Using Their String Names in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn