How to format a string by using dictionary

Format a string with dictionary

If you use a dictionary with only strings as keys instead of a tuple, you can make the string formatting even snazzier.

After the % character in each conversion specifier, you add a key enclosed in parentheses, which is followed by the other specifier elements:

phonebook = {'Beth': '9', 'Alice': '2', 'Cecil': '3'} print "Number is %(Cecil)s." % phonebook

This sort of string formatting can be very useful in template systems (in this case using HTML):


template = '''<html> 
              <head><title>%(title)s</title></head> 
              <body> #   w w w.ja va  2  s . c  om
              <h1>%(title)s</h1> 
              <p>%(text)s</p> 
              </body>''' 

data = {'title': 'My Home Page', 'text': 'Welcome to my home page!'} 
print template % data 

The code above generates the following result.





















Home »
  Python »
    Data Types »




Data Types
String
String Format
Tuple
List
Set
Dictionary