String formatting with dictionaries

David Bolen db3l at fitlinxx.com
Thu Jul 1 10:40:54 EDT 2004


tkpmep at hotmail.com (Thomas Philips) writes:

> I am aware that I can make it work by changing e to 
> e={'1':'one', '2': 'two'} 
> but I do want to find out 
> 
> a) what is needed make it work in its current form, and

What you just did above - use strings as keys in your dictionary.

> b) why it does not work in the seemingly obvious way I have written it
> above

Perhaps probably because your intuition isn't firmly grounded in Dutch
sensibilities?  Or I could just say "because that's not how the string
formatting operator works" but that doesn't help much does it :-)

If we come at it from your "obvious" comment, one could ask why you
think it treating it as a number is obvious?  When you write:

        "blah blah blah %(name)s blah blah" % some_dict

The formatting operator upon finding "%(name)s", looks up "name" in
the dictionary and then applies the "s" (string) format to it.  If you
think about it the formatting operator just has access to your format
string as, in fact, a string.  And in the specific case of dictionary
keys, the element in between the () is a label to be used (a sequence
of characters as per 2.3.6.2 in the library reference, and both there
and 7.1 in the tutorial show examples using string keys).

Now, there's no additional markup in the format string to indicate
that the dictionary key is anything other than a sequence of
characters, and since in general Python tries to avoid ever guessing
at what you mean, it just uses those characters directly.

In other words, you may see the "1" in the format string as a number,
but you've entered it into your program as part of a string, and
that's how Python (and the string formatting operator) see it.  Maybe
not what you desired, but it's how the formatting operator works in
this case.

-- David




More information about the Python-list mailing list