Python String Formatting With Dictionaries

In Python, you can use dictionaries instead of tuples to populate values via classic string formatting.

By Ryan McGreal. 144 words. Approximately a 0 minute read.
Posted January 04, 2012 in Blog.

My mind is duly blown. I never realized that the traditional printf-style string formatting in Python - the kind that uses the % operator - supports the use of a dictionary as well as a tuple.

The following works:

>>> data = {
    'title': 'Python String Formatting With Dictionaries',
    'author': 'Ryan McGreal',
    'summary': 'In Python, you can use dictionaries instead of tuples to populate values via classic string formatting.',
    'content': '

My mind is duly blown...', 'author_bio': 'Ryan McGreal lives in Hamilton with his family and works as a programmer and writer.', } >>> template = """ <span style="color: red">%(title)s</span>

%(title)s

By %(author)s

%(summary)s

%(content)s
%(author_bio)s
""" >>> print template % data

As an ultra-lightweight templating engine, this is pretty sweet: it's fast, simple, supports Unicode, and has no third-party dependencies.