Python: string substitution using dictionaries

A nice way to populate a string with values is to use a dictionary, which can be defined outside of the print statement.

The standard way is to write

>>> print "The temperature in %s is %f degrees" % ('celsius', 20)
"The temperature in celsius is 20 degrees"

Another way using dictionaries is as follows:

>>> data = {'unit': 'celsius', 'value':20}
>>> print "The temperature in %(unit)s is %(value)f degrees" % data
"The temperature in celsius is 20 degrees"

This is very convenient when you want to rephrase a sentence without changing the data structure:

>>> print "The temperature is %(value)f degrees (%(unit)s)." % data
"The temperature is 20 degrees (celsius)."
Please follow and like us:
This entry was posted in Python and tagged . Bookmark the permalink.

One Response to Python: string substitution using dictionaries

Leave a Reply

Your email address will not be published. Required fields are marked *