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
Release: 2024-12-11 11:54:11
Original
749 people have browsed it

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']}
Copy after login

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

get_ext['audio']  # ['mp3', 'wav']
Copy after login

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']
Copy after login

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

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

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']
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template