String formatting with dictionaries
me at privacy.net
Thu Jul 1 16:31:41 CEST 2004
tkpmep at hotmail.com (Thomas Philips) wrote in
news:b4a8ffb6.0407010600.1a18ff24 at posting.google.com:
> 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.
The mapping key is a sequence of characters, i.e. it already is a string.
Python is not converting it to a string, it is simply not converting it
into a number.
To make it work, you could subclass dict so that strings get converted to
integers automatically on lookup, or just convert the keys to strings:
print " %(1)s" % dict([(str(k),e[k]) for k in e])
More information about the Python-list