Joker
Joker

Reputation: 21

Passing arguments from variable - Python

I'm writing a python script. In the script I wrote a function with some arguments that all has defult values. Also in the script i have list of tuples, first item in each tuple its the name of the argument from the function, the second is the value. here is code for example:

def f(a=0, b=0, c=0):
    print(a), print(b), print(c)

args = [('a', 12), ('c', -64)]

Is there some way, when I call the method, to put the value 12 in the 'a' argument and the value -64 in the 'c' argument without do it manualy? (the value b remains 0).

Thanks for any Help!

Upvotes: 0

Views: 35

Answers (2)

Andrey RF
Andrey RF

Reputation: 342

def f(a=0, b=0, c=0):
    print(a), print(b), print(c)

args = [('a', 12), ('c', -64)]

f(**dict(args))

result:

a = 12
b = 0
c = -64

But better way to use dict

Upvotes: -1

DeepSpace
DeepSpace

Reputation: 81684

You can build a dictionary then unpack it with **:

f(**dict(args))

will output

12
0
-64

Upvotes: 5

Related Questions