Get dictionary-keys used to format a string

cgw at alum.mit.edu cgw at alum.mit.edu
Thu Mar 2 12:53:31 EST 2000


In article <m3g0u97fx4.fsf at atrus.jesus.cam.ac.uk>, Michael Hudson <mwh21 at cam.ac.uk> wrote:
> Michael =?iso-8859-1?Q?Str=F6der?= <michael.stroeder at inka.de> writes:
> 
>> Hence the example from the Python docs:
>> 
>> '%(language)s has %(count)03d quote types.' % vars()
>> 
>> I would like to extract the keys in the formatting string to a list.
>> Well I can parse it myself but is there a built-in function to
>> extract a list/tuple of the dictionary keys, e.g.
>> ['language','count'] in this case?
>> 
> 
> Don't think so, sorry.
> 
> Cheers,
> M.
> 

How about this approach?

#!/usr/bin/env python

class Malleable:
    def __str__(self):
        return ""
    def __int__(self):
        return 0
    def __long__(self):
        return 0L
    def __float__(self):
        return 0.0
        
class KeyKeeper:
    m=Malleable()
    def __init__(self):
        self.keylist=[]
    def __getitem__(self,key):
        self.keylist.append(key)
        return m


k=KeyKeeper()
fmt_string="%(language)s has %(count)03d quote types."
fmt_string%k

print k.keylist





More information about the Python-list mailing list