Search code examples
pythonpython-3.xfunctiondictionarymethods

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?


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.