2

What I want to do is this:

logged_in = {
    'logged_in': True,
    'username' : 'myself',
    }
print render_template('/path/to/template.html',
    **logged_in,
    title = 'My page title',
    more  = 'even more stuff',
    )

But that doesn't work. Is there any way to combine a dictionary expansion with explicit arguments, or would I need to define the explicit arguments in second dictionary, merge the two, and expand the result?

st-boost
  • 1,877
  • 1
  • 14
  • 17

2 Answers2

6

Keyword expansion must be at the end.

print render_template('/path/to/template.html',
    title = 'My page title',
    more  = 'even more stuff',
    **logged_in
)
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
  • I actually tried this before posting and it didn't work. You made me revisit it, and it turns out you're not allowed to put a comma after the last argument if it's an expansion. – st-boost Mar 28 '12 at 07:22
1

Yes, you just have it backwards. The keyword expansion must be at the end.

def foo(a,b,c,d):
   print [a,b,c,d]

kwargs = {'b':2,'c':3}
foo(1,d=4,**kwargs)
# prints [1, 2, 3, 4]

The above work because they are in proper order, which is unnamed arguments, named, then keyword expansion (while the * expression can go either before or after the named arguments but not after the keyword expansion). If you were to do these, however, it would be a syntax error:

 foo(1,**kwargs,d=4)
 foo(d=4,**kwargs,1)
 foo(d=4,1,**kwargs)
cwallenpoole
  • 79,954
  • 26
  • 128
  • 166