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

Victor Hooi victorhooi at gmail.com
Wed Nov 27 01:01:48 CET 2013


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



More information about the Python-list mailing list