DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Python Keyword Arguments

  • submit to reddit
        This 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 "<stdin>", 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