String formatting with dictionaries

Mel Wilson mwilson at the-wire.com
Thu Jul 1 10:30:35 EDT 2004


In article <b4a8ffb6.0407010600.1a18ff24 at posting.google.com>,
tkpmep at hotmail.com (Thomas Philips) wrote:
>Consider the following simple dictionary
>e={1:'one', 2: 'two'}
>e[1]
>>>>'one'
>
>However, If I attempt to print e[1] using a formatted string
>print " %(1)s" %e,
>
>I get a KeyError: '1'
>
>Clearly Python is converting the number 1 to the string '1' before
>looking it up in the dictionary.

   Not clear at all.  Any immutable value can be a
dictionary key.

   The mapping key is a sequence of characters in a format
string.. a slice of a string, you might say, and it will
only match a key that is a string.


>                                 Furthermore, this seems to happen
>only when creating formatted strings: the dictionary can be directly
>accessed as shown above. How can I modify my formatted string
>statement to correctly access the  dictionary.
>
>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
>b) why it does not work in the seemingly obvious way I have written it
>above

   It wouldn't be enough the make %(1)s retrive 'one' in the
dictionary e; you'd actually be interpreting Python
expressions inside the format string, and people would
require %(7-5)s to come out as two, just like e[7-5] did.

>>> f={'7-5':'three'}
>>> print "%(7-5)s" % f
three


        Regards.        Mel.



More information about the Python-list mailing list