Determining a replacement dictionary from scratch

Robert Brewer fumanchu at amor.org
Sun Jan 18 21:46:13 EST 2004


Dan wrote:
> I'd like to be able to take a formatted string and determine the
> replacement dictionary necessary to do string interpolation with it. 
> For example:
> 
> >>> str = 'his name was %(name)s and i saw him %(years)s ago.'
> >>> createdict( str )
> {'name':'', 'years':''}
> >>>
> 
> Notice how it would automatically fill in default values based on
> type.  I figure since python does this automatically maybe there is a
> clever way to solve the problem.  Otherwise I will just have to parse
> the string myself.  Any clever solutions to this?

If the only functionality you want is the ability to fill in default
values, you could try a variation on subclassing dict:

PythonWin 2.3.2 (#49, Oct  2 2003, 20:02:00) [MSC v.1200 32 bit (Intel)]
on win32.
>>> class DefaultDict(dict):
... 	def __init__(self, default):
... 		self.default = default
... 	def __getitem__(self, key):
... 		try:
... 			return dict.__getitem__(self, key)
... 		except KeyError:
... 			return self.default
... 		
>>> str = 'his name was %(name)s and i saw him %(years)s ago.'
>>> d = DefaultDict('???')
>>> d['years'] = 3
>>> str % d
'his name was ??? and i saw him 3 ago.'


Robert Brewer
MIS
Amor Ministries
fumanchu at amor.org




More information about the Python-list mailing list