Python Dict To String Example

When formatting a character string, if the character string template to be formatted contains multiple variables, then you should provide multiple variables in order. This method is suitable for the case where a small number of variables are contained in the string template like below.

>>> print('%s love %s' % ('I', 'python'))
I love python

But if the string template contains a large number of variables, this way of supplying variables in order is somewhat inappropriate. You can instead specify the variable by key in the string template and then set the value for the key in the string template through a dictionary as below.

>>> # use dict key in the string template. 
>>> str_tpl = '%(name)s love %(language)s' 
>>>
>>> # create a python dictionary object use above key.
>>> dict_val = {'name':'Jerry', 'language':'Python'}
>>>
>>> # Use dictionary to pass in value for key in string template 
>>> print(str_tpl % dict_val)
Jerry love Python
>>> 
>>> # create another dictionary object with same key.
>>> dict_val = {'name':'Tom', 'language':'Java'}
>>> 
>>> print(str_tpl % dict_val)
Tom love Java

Leave a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.