Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I pass variable keyword arguments to a function in Python?

How can I pass dictionary keys (or other attributes/values) as keywords for keyword arguments?

The function I want to pass arguments to takes keyword arguments:

func(arg1= "foo", arg_a= "bar", firstarg= 1)

I have a lot of arguments to pass to it, so I'd like to loop it (or if it's possible without a loop, even better):

arguments_dictionary={'arg1': "foo", 
                      'arg_a': "bar",
                       ...}

for keyword, value in arguments_dictionary.items():
  func(keyword= value)

Sadly, keyword= is not recognized as 'arg1'. How can I make this work?

like image 362
Kalle Nijs Avatar asked Jun 25 '26 11:06

Kalle Nijs


1 Answers

Assuming you want to call func a single time:

def func(arg1="foo", arg_a= "bar", first_arg=1):
   print(arg1, arg_a, first_arg)

arguments_dictionary = {
  'arg1': "foo", 
  'arg_a': "bar",
  'first_arg':42
   }

func(**arguments_dictionary)
like image 116
bruno desthuilliers Avatar answered Jun 28 '26 01:06

bruno desthuilliers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!