1

I am reading Programming Python and can't figure out what the **D mean in the following codes:

>>> D = {'say': 5, 'get': 'shrubbery'}
>>> '%(say)s => %(get)s' % D
'5 => shrubbery'
>>> '{say} => {get}'.format(**D)
'5 => shrubbery'

I googled **kwargs in python and most of the results are talking about to let functions take an arbitrary number of keyword arguments.

The string.format(**D) here doesn't look like something to let function take an arbitrary number of keyword arguments because I see the dictionary type variable D is just one argument. But what does it mean here?

hxin
  • 938
  • 2
  • 12
  • 25
  • 3
    Have you seen http://stackoverflow.com/questions/3394835/args-and-kwargs? – gypaetus Aug 29 '13 at 23:53
  • Yes, I did look at that question but I could not make the connections there. The **kwargs there only appears in function def, not when you call the functions or the methods. – hxin Aug 30 '13 at 01:20
  • I overlooked the answer to question http://stackoverflow.com/q/1415812/2719588 given by Alex Martelli. He made a very good point of _"As for using **kw in a call, "..._ – hxin Sep 29 '13 at 14:09

3 Answers3

4

Argument unpacking seems to be what you're looking for.

Prashant
  • 1,014
  • 11
  • 28
3

**D is used for unpacking arguments. It expands the dictionary into a sequence of keyword assignments, so...

'{say} => {get}'.format(**D)

becomes...

'{say} => {get}'.format(say = 5, get = shrubbery)

The **kwargs trick works because keyword arguments are dictionaries.

smci
  • 32,567
  • 20
  • 113
  • 146
James K
  • 3,692
  • 1
  • 28
  • 36
2

Short answer, I'm sure someone will come up with a dissertation later on.

**D here means that dictionary D will be used to fill in the "named holes" in the string format. As you can see, {say} got replaced by 5 and {get} got replaced by shrubbery.

Actually, it is the same mechanism as the one used for passing an arbitrary number of parameters to a function; format expects as many parameters as the "holes" in the string. If you want to wrap them up in a dictionary, that's how you do it.

For more information, check keyword arguments and unpacking, in Python's documentation, as Prashant suggested.

nickie
  • 5,608
  • 2
  • 23
  • 37
  • The 3 answers combined gave me a clear understanding of what it is. Thanks for your just detailed enough explanation and easy to understand answer! – hxin Aug 30 '13 at 02:15