syntax philosophy

Tuang tuanglen at hotmail.com
Wed Nov 19 14:48:17 EST 2003


"Terry Reedy" <tjreedy at udel.edu> wrote in message news:<v7GdnQeHauxYWyeiRVn-hQ at comcast.com>...
> "Tuang" <tuanglen at hotmail.com> wrote in message
> news:df045d93.0311172120.7e753552 at posting.google.com...
> > $dict{$color}++
> > to count up what you find.
> 
> Your wish is Python's command:
> 
> class cdict(dict):
>   def __getitem__(self, key):
>     try:
>       return dict.__getitem__(self, key)
>     except KeyError:
>       return 0
> 
> h=cdict()
> for item in [1,1,2,3,2,3,1,4]:
>   h[item]+=1
> 
> >>> h
> {1: 3, 2: 2, 3: 2, 4: 1}
> 
> > $dict{$salesperson} += $amount
> 
> Trivial modification:
> 
> t=cdict()
> for key,amt in ((1,2), (1,3), (2,5), (3,1), (3,2), (3,3)):
>   t[key] += amt
> 
> >>> t
> {1: 5, 2: 5, 3: 6}
> 

Nice. I like that. It appears that in Python it pays to think at a
slightly higher level of abstraction than in Perl. Put a little extra
time into creating a little tool for the job the first time, then
reuse it the next time. I do that with Perl code snippets, but using
small classes or functions instead appeals to me.




More information about the Python-list mailing list