Home > Backend Development > Python Tutorial > How Can I Select Variables in Python Using a String Input?

How Can I Select Variables in Python Using a String Input?

Patricia Arquette
Release: 2024-12-21 01:17:09
Original
868 people have browsed it

How Can I Select Variables in Python Using a String Input?

Selecting Variables by String Name

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

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

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

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

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()
Copy after login

This allows for easy modification of recognized file types:

get_ext.types['binary'] = ['bin', 'exe']
get_ext('binary')  # returns ['bin', 'exe']
Copy after login

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!

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