Determining a replacement dictionary from scratch

Christophe Delord no.spam
Sun Jan 18 21:09:17 CET 2004


On 18 Jan 2004 11:16:31 -0800, Dan wrote:

> Hello,
> 
> 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?
> 
> Thanks 
> -dan

You can use the % operator to look for such constructions. You just
need to define the __getitem__ method of a class to store the
variable names. What about this function:

def createdict(format):
    class grab_variables:
        def __init__(self):
            self.variables = {}
        def __getitem__(self, item):
            self.variables[item] = ''
    g = grab_variables()
    format%g
    return g.variables

print createdict('his name was %(name)s and i saw him %(years)s ago.')

{'name': '', 'years': ''}


Best regards,
Christophe.



More information about the Python-list mailing list