Determining a replacement dictionary from scratch

Jeff Epler jepler at unpythonic.net
Sun Jan 18 15:27:10 EST 2004


On Sun, Jan 18, 2004 at 07:34:07PM -0000, Dave Benjamin wrote:
> Here's a solution that uses a regular expression. It only handles strings
> and doesn't cache the regular expression; I'll leave this up to you. =)

Of course, since it uses regular expressions it's also wrong...

>>> createdict("%%(foo)s")
{'foo': ''}

This version might be more correct:

pat = re.compile("%\([^)]*\)s|%%")

def createdict(fmt):
	keys = [x[2:-2] for x in pat.findall(fmt) if x != '%%']
	return dict(zip(keys, [''] * len(keys)))

Here's another way, one I like better:
	class D:
		def __init__(self): self.l = []
		def __getitem__(self, item): self.l.append(item)

	def createdict(fmt):
		d = D()
		fmt % d
		return dict(zip(d.l, [''] * len(d.l)))
.. I like it better because it uses the exact same logic to determine
the needed names as it will when the string is actually formatted.

Jeff




More information about the Python-list mailing list