0

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")
martineau
  • 112,593
  • 23
  • 157
  • 280
Johannes
  • 23
  • 2

2 Answers2

2

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")
martineau
  • 112,593
  • 23
  • 157
  • 280
balderman
  • 21,028
  • 6
  • 30
  • 43
0

If it's a global variable, you can use this:

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


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

obj = My_Class(globals()['object_dictionary'])

output:

{'car': 'some_car', 'house': 'some_house', 'animal': 'some_animal'}
I'mahdi
  • 11,310
  • 3
  • 17
  • 23