0

I am calling a function

foo(x,y0=y[0],y1=y[1],y2=y[2],...,y<d>=y[<d>])

where <d> is a large number that may vary from call to call. All arguments except x are keyword arguments. I didn't write foo myself, so I cannot just pass y as a list instead. Is there an automated way to split a list into keyword arguments?

3 Answers 3

6

First, build a list of name, value pairs, then convert that to a dictionary and pass it to the function.

y_vals = [ 1, 2, 3, 'a', 'b', 'c' ]
arg_dict = dict(('y%d' % i, v) for i, v in enumerate(y_vals))
foo(x, **arg_dict)
Sign up to request clarification or add additional context in comments.

2 Comments

This could be made a bit more concise as a dict comprehension: arg_dict = { 'y%d' % i: v for i, v in enumerate(y_vals)}
This is exactly what I was looking for. Beautiful!
4

Use * for passing unpacked arguments from a list, You can send in normal arguments in place of keyword arguments, just make sure you pass them in proper order, for e.g:

def foo(x, y1=None, y2=None, y3=None, y4=None, ... , yN=None):
  # func stuff

You can pass a list to the function unpacked, like:

arguments = ["arg-y1", "arg-y2", "arg-y3", ... , "arg-yN"]
foo (x, *arguments)

As they are keyword arguments, they will have some default value. If you want to pass only a few specific values, you can use the Dictionary and ** for kw:

kwargs = {"y1": "arg-y1", "y3": "arg-Y3" }
foo (x, **kwargs)

Comments

3

You can use **kwargs to let your functions take an arbitrary number of keyword arguments ("kwargs" means "keyword arguments"):

>>> def print_keyword_args(**kwargs):
...     # kwargs is a dict of the keyword args passed to the function
...     for key, value in kwargs.iteritems():
...         print "%s = %s" % (key, value)

... 
>>> print_keyword_args(first_name="John", last_name="Doe")
first_name = John
last_name = Doe

You can also use the **kwargs syntax when calling functions by constructing a dictionary of keyword arguments and passing it to your function:

>>> kwargs = {'first_name': 'Bobby', 'last_name': 'Smith'}
>>> print_keyword_args(**kwargs)
first_name = Bobby
last_name = Smith

The Python Tutorial contains a good explanation of how it works, along with some nice examples.

For your case to convert list to keyword arguments :

# y is a list with arguments stored.
kwargs = {}
for arg in range(len(y)):
    kwargs['y'+str(arg)] = y[arg]

foo(**kwargs)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.