%
Quinn Dunkan
quinn at photo.ugcs.caltech.edu
Fri Apr 30 23:17:23 EDT 1999
On Fri, 30 Apr 99 01:30:12 GMT, Phil Hunt <philh at vision25.demon.co.uk> wrote:
>
>Consider the % operator, eg:
>
> 'All %(a)s eat %(b)s' % {'a':'cows', 'b':'grass'}
>
>If the dictionary doesn't have all the relevant keys, an error
>occurs. Is it possible for me to change the behaviour of this so that
>if a key doesn't occur a default value of '' is assumed?
Well, my way is to make my own dictionary:
import UserDict
class DefaultDict(UserDict.UserDict):
def __init__(self, dict, default=''):
self.default = default
self.data = dict
def __getitem__(self, key):
return self.data.get(key, self.default)
'All %(a)s eat %(b)s' % DefaultDict({'a': 'cows', 'b': 'grass'})
Union dictionaries (search through several dicts) are particularly useful for
%. There's even an implementation in C from DC (MultiMapping.so)
More information about the Python-list
mailing list