String formatting with dictionaries

Thomas Philips tkpmep at hotmail.com
Thu Jul 1 10:00:13 EDT 2004


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. 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

Sincerely
Thomas Philips



More information about the Python-list mailing list