Reputation: 25
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
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