a clean way to define dictionary

Michele Simionato mis6 at pitt.edu
Thu Jun 19 12:31:44 EDT 2003


Alexander Schmolck <a.schmolck at gmx.net> wrote in message news:<yfsof0v880w.fsf at black132.ex.ac.uk>...
> Maybe I'm a bit blinkered, but right now I can't see how
> 
>     dict(foo=1, bar='sean')
> 
> is so much better/more convinient than
> 
>     {'foo':1, bar:'sean'}
> 
> that it justifies forcing people to learn a new redundant and less general
> dictionary creation syntax that at least hinders customizing dictionary
> instantiation like in
> 
>   counts = dict(default=0)
>   for item in seq:
>       counts[item] += 1
> 
> To get the first behavior you have to write a 1-line function, for the second
> you have to subclass (and presumably incur a noticeable performance penalty).
> Also the first precludes adding further constructor options, while the second
> doesn't.
> 
> 
> 'as

I do think you have a point here. Nevertheless, I wonder about the
"noticeable performance penality" due to subclassing. I tried this
dictionary:

class mydict(dict):
    def __new__(cls,d,default=0): 
        #absolutely trivial, doing nothing with the default argument
        return super(mydict,cls).__new__(cls,d)

d=dict([(i,str(i)) for i in range(1000)])
m=mydict([(i,str(i)) for i in range(1000)])

And I have measured the access times for 'd' and 'm' with timeit. There is no
noticeable difference for getting a value (<1%); setting a value is slower
by a 7-8%. Not a big deal. I get more or less the same numbers for bigger
or smaller dictionaries. Nevertheless, I haven't tried many dictionaries,
maybe there are cases where the performance is worse.

If somebody wants to experiment and report here few numbers, it would be
interesting.

                                                   Michele




More information about the Python-list mailing list