0

I am given a dictionary, whose keys are equal to function parameters and their corresponding values are the arguments for the function. Is there a elegant way to pass the values inside the dictionary to its respective parameter?

The code as written below is functional, however not very elegant, in particular, if the functions have many parameters and depending on the situation not all of them are needed. The code became then very repetitive and longish.

The most elegant way at the moment seems to be to simply wrap the repetitive, longish function in its own function, leaving my function f behind containing only nice, readable, self explaining code.

def f(func, d):
    if func == "g1":
        # g1(a= d['a'], b=d['b') # functional, but doesn't look nice
        pass
    elif func == "g2":
        # g2(a2= d['a2'], b2=d['b2'], c2= d['c2']) # functional, but doesn't look nice
        pass
    elif func == "g3":
        wrapper_for_g3(d)

def g3():
    pass

def g1(a, b):
    pass

def g2(a2, b2, c2):
    pass

def wrapper_for_g3(d): #100 parameters, same problem as above
    g3(a1 = d['a1'],  
       # ...
       # ...
       a100=d['a100'],
       )

d1 = dict()
d1["a"] = 1
d1["b"] = 2

d2 = dict()
d2["a2"] = 2
d2["b2"] = 4
d2["c2"] = 8

f("g1")
f("g2")
Imago
  • 521
  • 6
  • 29

1 Answers1

2

You can use the double asterisks in Python

def f(func, d):
  func(**d)
navotgil
  • 329
  • 5
  • 16