Python dictionary partial formatting

Python has powerfull string formating implementation, one of them is a dictionary based approach where you can specify dictionary keys and they will be substituted with related dictinary values:

>>> template = "Hello {name} {surname}"
>>> template.format( **{'name': 'John', 'surname': 'Doe'} )
'Hello John Doe'

But this approach requires all keys specified in template to be present in dictionary, otherwise you get KeyError exception:

>>> template = "Hello {name} {surname}"
>>> template.format( **{'name': 'John'} )
Traceback (most recent call last):
  File "<input>", line 1, in <module>
KeyError: 'surname'

How to fix that and still use dictionary ?

You can define custom formatter subclass the dictionary class with overwriten __missing__ method that should return desired default value, even an empty string ‘’.

>>> import string
>>> class FormatDict(dict):
...     def __missing__(self, key):
...         return '~'
>>> formatter = string.Formatter()
>>> template = "Hello {name} {surname}"
>>> formatter.vformat(template, (), FormatDict({'name': 'John', 'surname': 'Doe'}))
'Hello John Doe'
>>> formatter.vformat(template, (), FormatDict({'name': 'John'}))
'Hello John ~'

See other python formatting examples are here