Search code examples
pythondictionaryfunctional-programmingnamed-parameters

How to get a string from a dictionary and use it as a named parameter in any function?


I have a dictionary in python,

mapper = {'my_func': ['a', 'b', 'c', 'd']}

I want to call a function which takes a, b, c, d and e parameters -

functn(a, b, c, d, e=None)

The parameters a, b, c, d is what I want to use while calling the function, and not e, and those parameter names are defined in that dictionary.

How can I parse the dictionary values and use them as named parameters in the function, while passing some values to each one of them?

Eg:

I can get named parameter a, by doing this -

mapper['my_func'][0]

But how to use that value as a named parameter in the above function?

Any help?


Solution

  • You can do this in a couple of steps:

    mapper = {'my_func': [1, 2, 3, 4]}
    
    def functn(v, w, x, y, z):
        return v + w + x + y + z
    
    # create dictionary of arguments to values
    d = {**dict(zip(list('vwxy'), mapper['my_func'])), **{'z': 5}}
    
    # unpack dictionary for use in function
    res = functn(**d)  # 15