Passing multiple arguments to a function with a dictionary

Question:

I have a set of functions fun1, fun2, fun3 that I’m calling from a main file. Each of them are using some variables stored in my main file (where I’m also calling the functions):

a = 2
b = 3
c = 12
d = "abc"
e 12
f = "jh4jer"
g = np.array(2,3)

fun1(a,b,c,d,e,f)
fun2(d,e,f,g)
fun3(a,e,f,g)

I would like to create a sort of structure (in my opinion a dictionary would be perfect) to store all my variables to I can pass only this dictionary to my functions, something like that:

dictionary1 = {'a':a, 'b':b, 'c':c, 'd':d, 'e':e, 'f':f, 'g':g}
fun1(dictionary1)
fun2(dictionary1)
fun3(dictionary1)

Can I do something like that or there is a smarter way? Is it going to be an issue if I pass more arguments to a function with respect to the ones required?

Asked By: TFAE

||

Answers:

You can try this way –

obj: dict = {
    "a": 2, "b": 3, "c": 12, "d": "abc", "e": 12, "f": "jh4jer", "g": np.array(2,3)}

# pass full object to function
fun1(obj)

# pass only required variables to fun2
fun2_obj = {"d": obj["d"], "e": obj["e"], "f": obj["f"], "g": obj["g"]}
fun2(fun2_obj)


# pass only required variables to fun3
fun3_obj = {"a": obj["a"], "e": obj["e"], "f": obj["f"], "g": obj["g"]}
fun3(fun3_obj)
Answered By: Shapon Sheikh

You can pass the whole dictionary to each function and just pick up in a function the arguments it requires. For example:

var1 = 123
var2 ='hello'
var3 = 456

d = {'a': var1, 'b': var2, 'c': var3}

def func1(x):
    print(x['a'])
    print(x['c'])
    
def func2(z):
    print(z['b'])
        
func1(d)
func2(d)
Answered By: user19077881
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.