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")

1 Answer 1

3

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")
Sign up to request clarification or add additional context in comments.

4 Comments

But this will change the original dictionary. What if the dictionary is set by a user such that you cannot change it by making a dict of dicts?
@PCM that is a good question. Lets hear the OP and understand if that can work for him.
im sorry, it says I need more reputation to upvote
@Johannes No problem.. wait until you will have enough reputation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.