string formatting with missing dictionary key

gyro gyromagnetic at
Mon Jan 13 18:11:53 CET 2003

A nice feature of later versions of Python is the ability to get and set 
undefined keys/values in dictionaries (dict.get,dict.setdefault).

However, this mechanism doesn't seem to be usable directly for a case in 
which I am interested. I have an application in which I have a 
formatting 'template' and a dictionary from which I get values for the 
In certain situations, there is a dictionary that doesn't have one or 
more keys specified in the formatting string. In these cases, I get the 
expected 'KeyError'.

As a very simple example, consider

mdict = {'a':1, 'b':2, 'c':3}
fline = "%(a)s ; %(d)s ; %(e)s" % mdict

Suppose you want any undefined keys to have the value 'default', i.e.

fline == "1 ; default ; default"

As far as I can see, there is no direct way to use .get/.setdefault to 
do something like

"%(a)s ; %(d)s ; %(e)s" % mdict.setmissingkeyval('default')

so I have come up with the following workaround:

 >>> mdict = {'a':1, 'b':2, 'c':3}
 >>> fline = ''
 >>> while not fline:
...   try:
...     fline = "%(a)s ; %(d)s ; %(e)s" % mdict
...   except KeyError,e:
...     dummy = mdict.setdefault(e.args[0],'default')

Is there a better or more Pythonic way to do this?

Thanks for your help.


More information about the Python-list mailing list