string formatting with missing dictionary key
Peter Abel
p-abel at t-online.de
Mon Jan 13 18:13:14 EST 2003
gyro <gyromagnetic at excite.com> wrote in message news:<3e22f35a at news.ColoState.EDU>...
> Hi,
> 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
> template.
> 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.
>
> -g
Hi gyro
some more lines at the beginning,
but then, i think a little bit more Pythonic:
>>> class myDict:
... def __init__(self,default='default'):
... self.mdict={}
... self.default=default
... def __setitem__(self,key,value):
... self.mdict[key]=value
... def __getitem__(self,key):
... return self.mdict.get(key,self.default)
... def keys(self):
... return self.mdict.keys()
... def values(self):
... return self.mdict.values()
... def items(self):
... return self.mdict.items()
... def update(self,dict):
... self.mdict.update(dict)
...
# An Example
>>> mdict=myDict('AnyDefaultValue')
>>> mdict.update({'a':1,'b':2,'c':3})
>>> mdict.items()
[('a', 1), ('c', 3), ('b', 2)]
>>> mdict
<__main__.myDict instance at 0x00D7AE40>
>>> fline = "%(a)s ; %(d)s ; %(e)s" % mdict
>>> fline
'1 ; AnyDefaultValue ; AnyDefaultValue'
>>>
Remark, i think <def keys>, <def values>, <def items> are not nessesarily
to implement.
Cheers Peter!
More information about the Python-list
mailing list