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

Bengt Richter bokr at oz.net
Thu Mar 28 21:46:45 EST 2002


On Thu, 28 Mar 2002 18:09:39 -0500, "Steve Holden" <sholden at holdenweb.com> wrote:

>"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.
>
empty_dict_with_default = {:default}
with_one_key_value_pair = {:default, key:value}

A little tweak in the grammar might do it?

Regards,
Bengt Richter
Regards,
Bengt Richter



More information about the Python-list mailing list