Bananach Bananach - 28 days ago 7
Python Question

How to pass large number of keyword arguments automatically in python

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?

cco cco
Answer

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)