Default arg for dict() (was Re: Sorting distionary by value)
Steve Holden
sholden at holdenweb.com
Thu Mar 28 18:09:39 EST 2002
"John Machin" <sjmachin at lexicon.net> wrote ...
> philh at comuno.freeserve.co.uk (phil hunt) wrote in message
news:<slrnaa6b9s.bed.philh at comuno.freeserve.co.uk>...
> > On Wed, 27 Mar 2002 23:02:20 -0500, Peter Hansen <peter at engcorp.com>
wrote:
> > >Jim Dennis wrote:
> > >> freq = {}
> > >> if word in freq: freq[word] += 1
> > >> else: freq[word] =
1
> >
> > >Something like freq[word] = freq.get(word, 0) + 1
> >
> > IIRC in Awk you can just say: freq[word] ++ and it works
> > correctly even when there is no pre-existing index of word in freq.
> >
> > IMO it's a pity Python isn't like that.
>
> Python *could* be made like that with the explict dict() constructor
> ... something like:
>
> freq = dict(default=0)
> ...
> freq[word] += 1
This was a feature of the Icon language. But Icon had no explicit literal
representation for dictionaries (or tables, as I think they were called) as
far as I can remember, so it was easy to make the default value an argument
to a constructor function. It's not obvious how you could indicate the
default without calling a method.
regards
Steve
More information about the Python-list
mailing list