Python Keyword Arguments
Join the DZone community and get the full member experience.
Join For FreeThis is something I always forget how to do, and it's kind of hard to Google or search the Python docs because you can't search for **.
The point is, when using **kwargs, you have to use the ** prefix not only in the function definition, but also in the call, prefixed to the variable you want to use as a keyword dictionary.
>>> d = dict(zip(list('123'),list('abc')))
>>> d
{'1': 'a', '3': 'c', '2': 'b'}
>>> def printkwargs(**kwargs):
... for k,v in kwargs.items(): print k,v
...
>>> printkwargs(**d)
1 a
3 c
2 b
>>> printkwargs(d)
Traceback (most recent call last):
File "", line 1, in ?
TypeError: printkwargs() takes exactly 0 arguments (1 given)
>>> # you have to tell python that you want the argument to be treated as a keyword dictionary by prefixing it with **
>>> # more info at http://mail.python.org/pipermail/python-list/2006-March/332182.html
Python (language)
Opinions expressed by DZone contributors are their own.
Comments