string formatting with missing dictionary key

Gillou nospam at bigfoot.com
Tue Jan 14 00:14:54 CET 2003


"gyro" <gyromagnetic at excite.com> a écrit dans le message de news:
3e22f35a at news.ColoState.EDU...
> Hi,

>
> Is there a better or more Pythonic way to do this?
>
> Thanks for your help.
>
> -g
>

Perhaps subclassing an UserDict that returns a default value on a missing
key may do the job you expect.

>>> from UserDict import UserDict
>>> class MyDict(UserDict):
...  def __getitem__(self, k):
...   return self.data.get(k, 'no data')
...
>>> d = {'one' : 1, 'two': 2}
>>> md = MyDict(d)
>>> md['one']
1
>>> md['two']
2
>>> md['something_else']
'no data'
>>>

--Gilles







More information about the Python-list mailing list