3

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?

1
  • func(**arguments_dictionary)... Remove the loop Commented Jun 22, 2018 at 13:48

1 Answer 1

13

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)
Sign up to request clarification or add additional context in comments.

2 Comments

Strange how SO works... Sometimes you take hours writing a clear, detailed answer with in-depth explanations of some arcane feature and don't even get an upvote, then you write a minimal answer on a beginner-level question and get five upvotes in a couple minutes <g>
SO is fundamentally broken for just that. It's simply too large of a community for its own good.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.