%

Phil Hunt philh at vision25.demon.co.uk
Sun May 2 21:36:15 EDT 1999


In article <slrn7iksi3.r36.quinn at photo.ugcs.caltech.edu>
           quinn at photo.ugcs.caltech.edu "Quinn Dunkan" writes:
> 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)

That's neat.

One of the nice things about Python is that you can write stuff like 
this in a small amount of code -- I bet the equivalent in C++ or Java 
would be somewhat longer.

This answers the other question I had: how do I run a for loop over
a dictionary so that it loops over the elements sorted by key. Presumably
I'd just override the items() method in DefaultDict.

> '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)
> 

-- 
Phil Hunt....philh at vision25.demon.co.uk





More information about the Python-list mailing list