Python String Formatting - passing both a dict and string to .format()

Chris Kaynor ckaynor at
Wed Nov 27 01:21:27 CET 2013

On Tue, Nov 26, 2013 at 4:01 PM, Victor Hooi <victorhooi at> wrote:

> Hi,
> I'm trying to use Python's new style string formatting with a dict and
> string together.
> For example, I have the following dict and string variable:
>     my_dict = { 'cat': 'ernie', 'dog': 'spot' }
>     foo = 'lorem ipsum'
> If I want to just use the dict, it all works fine:
>     '{cat} and {dog}'.format(**my_dict)
>     'ernie and spot'
> (I'm also curious how the above ** works in this case).

> However, if I try to combine them:
>     '{cat} and {dog}, {}'.format(**my_dict, foo)
>     ...
>     SyntaxError: invalid syntax

Here you almost have it right. If you flip the arguments around to look
    '{cat} and {dog}, {}'.format(foo, **my_dict)
it will work as you expect.

The issue is that you cannot specify positional arguments (foo) after
keyword arguments (**my_dict).

In the code you tried, what Python is doing is:
    '{cat} and {dog}, {}'.format(cat=ernie, dog=spot, foo)
which, if tried, provides the nicer error message of "SyntaxError:
non-keyword arg after keyword arg".
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <>

More information about the Python-list mailing list