Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Call functions using dictionaries in python

Let’s say that I have this pseudo code:

x11 = {
    "exec": {
        "test1": "test1"
    },
    "mount": {
        "test2": "test2"
    },
    "unmount": {
        "test3": "test3"
    },
}

def get_exec(dict1):
    return dict1["test1"]

def get_mount(dict1):
    return dict1["test2"]

def get_unmount(dict1):
    return dict1["test2"]

x1 = ["exec", "mount", "unmount"]

for elem in x1:
    e1 = x11.get(elem)
    get_e = {
        "exec": get_exec(e1),
        "mount": get_mount(e1),
        "unmount": get_unmount(e1),
    }

    get_e[elem]

Basically, I am trying to avoid a lot of if conditions and want to use a dictionary and call the right function in each iteration. But this what i have is not working becuase then the dict is being called, it is going to each function and do operations. Basically, in my case each function is checking different keys and when e1 is passed to the function (which is valid only in the "exec" case, then it is failing on other function…

Is there a way to have something similar which works?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You mustn’t call your functions when defining your dict:

for elem in x1:
    e1 = x11.get(elem)
    get_e = {
        "exec": get_exec,
        "mount": get_mount,
        "unmount": get_unmount,
    }

    get_e[elem](e1)

Call the function after you have selected it.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading