0

I'm learning formatting expressions from a book and i have a question:

'{num} = {title}'.format(**dict(num=7, title='Strings'))

in the line above why are there two * before dict?? what do they represent?

the book didn't even mention this type of formatting expression and suddenly it was in the examples!!

senshin
  • 10,022
  • 7
  • 46
  • 59
mohsentux
  • 383
  • 1
  • 3
  • 11
  • While the linked duplicate does indeed explain the `**`, the real thing to know about your specific example is that the `dict()` is unnecessary. You'd get the exact same results with `format(num=7, title='Strings')`. Creating a dict just to immediately unpack it is silly (it might have made sense if it was a dict comprehension). – Blckknght Dec 19 '15 at 00:24
  • 1
    This is also a patently ridiculous use, since they're passing keyword args to make, then unpack a `dict`, when they could just pass the keyword args directly. – ShadowRanger Dec 19 '15 at 00:24

1 Answers1

0

The Principles

Python functions allow keyword arguments. For example this function:

def sub(a, b):
    return a - b

can be called like this:

>>> sub(b=10, a=4)
-6

If you have the arguments in a dictionary:

>>> args = {'a': 4, 'b': 10}

you can use the ** syntax to achieve the same:

>>> sub(**args)
-6

This is called unpacking because the items in the dictionary are used individually as arguments.

Your Example

Your example is over complicated. This would work:

'{num} = {title}'.format(num=7, title='Strings')

No need for using ** and a dictionary. The format() methods works like normal function and can be used with keyword arguments directly. The values 7 and Strings are put into a dictionary just be taken out again immediately.

Mike Müller
  • 82,630
  • 20
  • 166
  • 161