Home > Backend Development > Python Tutorial > How Can I Access a Predefined List Based on a String Input in Python?

How Can I Access a Predefined List Based on a String Input in Python?

Susan Sarandon
Release: 2024-12-18 20:42:17
Original
467 people have browsed it

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

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

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

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

This allows you to modify file types dynamically.

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 Access a Predefined List Based on a String Input 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