Default arg for dict() (was Re: Sorting distionary by value)
John Machin
sjmachin at lexicon.net
Thu Mar 28 21:29:15 EST 2002
"Steve Holden" <sholden at holdenweb.com> wrote in message news:<hpNo8.6269$Ou.4347 at atlpnn01.usenetserver.com>...
> "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.
>
See above: freq = dict(default=0)
I think that I'm proposing indicating the default by having a keyword
argument ("default")on the new-in-2.2 constructor ("dict"); what do
you think that I meant?
More information about the Python-list
mailing list