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


V

Victor Hooi

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

I also tried with:

'{0['cat']} {1} {0['dog']}'.format(my_dict, foo)
...
SyntaxError: invalid syntax

However, I found that if I take out the single quotes around the keys it then works:

'{0[cat]} {1} {0[dog]}'.format(my_dict, foo)
"ernie lorem ipsum spot"

I'm curious - why does this work? Why don't the dictionary keys need quotes around them, like when you normally access a dict's elements?

Also, is this the best practice to pass both a dict and string to .format()? Or is there another way that avoids needing to use positional indices? ({0}, {1} etc.)

Cheers,
Victor
 
Ad

Advertisements

S

Steven D'Aprano

'{0['cat']} {1} {0['dog']}'.format(my_dict, foo) ...
SyntaxError: invalid syntax

It's a syntax error because you are using the same quotes. You have:

'{0['cat']} {1} {0['dog']}'


which is parsed as:

STR '{0['
NAME cat
STR ']} {1} {0['
NAME dog
STR ']}'

which isn't legal. You can't write:

"foo"len

either.

As for why you don't need to quote the keys inside the string format min-
language, that is how the mini-language is designed, and it is for
convenience and to avoid the sort of trouble you're having now.

Also, is this the best practice to pass both a dict and string to
.format()? Or is there another way that avoids needing to use positional
indices? ({0}, {1} etc.)

I'd do it like this:

py> mydict = {'cat': 42, 'dog': 23, 'parrot': 99}
py> '{cat} and {dog}, {}'.format('aardvark', **mydict)
'42 and 23, aardvark'
 
M

Michael Torrie

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

This is a syntax error because of the way that the ** unpacks the
dictionary. For this not to be a syntax error, foo has to be before
my_dict. This is because in parameter passing, keyword args are always
passed last. In general I don't think you want to unpack the dictionary
in this case.
I also tried with:

'{0['cat']} {1} {0['dog']}'.format(my_dict, foo) ... SyntaxError:
invalid syntax

This is a syntax error because the cat and dog are not valid python
keywords. A string is anything between two delimiters. So your command
looks to python like this:

'{0[' cat ']} {1} {0[' dog ']}'.format(my_dict, foo)

If you have a proper syntax-highlighting editor you'll see right away
that cat and dog are not within the string delimiters.

This would work, however:

"{0['cat']} {1} {0['dog']}".format(my_dict, foo)
However, I found that if I take out the single quotes around the keys
it then works:

'{0[cat]} {1} {0[dog]}'.format(my_dict, foo) "ernie lorem ipsum
spot"

I'm curious - why does this work? Why don't the dictionary keys need
quotes around them, like when you normally access a dict's elements?

I suppose it's because the string formatter simply doesn't require it.
Also, is this the best practice to pass both a dict and string to
.format()? Or is there another way that avoids needing to use
positional indices? ({0}, {1} etc.)

Can't you just list them as separate arguments to format? Like you did
in your working example?
 
Ad

Advertisements

C

Chris Kaynor

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
like:
'{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".
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top