Question

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?

Was it helpful?

Solution 3

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.

OTHER TIPS

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

**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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top