Default arg for dict() (was Re: Sorting distionary by value)

John Machin sjmachin at lexicon.net
Thu Mar 28 15:30:11 EST 2002


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



More information about the Python-list mailing list