Johannes
Johannes

Reputation: 25

How to specify a variable or dictionary with a string?

i want to create an object of My_Class and want to tell it with a string what dictionary to get. Is there a better way than to do it with if?

object_dictionary = {
    "car" : "some_car",
    "house" : "some_house",
    "animal" : "some_animal"
}

class My_Class:
    def __init__(self, string):
        if string == "object_dictionary":
            self.dictionary = object_dictionary

obj = My_Class("object_dictionary")

If I want to choose between more dictionaries this will be inconvenient. How can I do this?

object_dictionary = {
    "car" : "some_car",
    "house" : "some_house",
    "animal" : "some_animal"
}

class My_Class:
    def __init__(self, string):
        self.dictionary = string

obj = My_Class("object_dictionary")

Upvotes: 0

Views: 427

Answers (1)

balderman
balderman

Reputation: 23815

Use dict of dicts. See below

dicts = {
    "this_dictionary": {
        "car": "some_car",
        "house": "some_house",
        "animal": "some_animal"
    },
    "that_dictionary": {
        "12": "ttt"
    }
}



class MyClass:
    def __init__(self, dict_name):
        self.dictionary = dicts.get(dict_name, {})


obj = MyClass("that_dictionary")

Upvotes: 3

Related Questions