Sorting distionary by value

phil hunt philh at comuno.freeserve.co.uk
Thu Mar 28 19:48:22 EST 2002


On 28 Mar 2002 15:19:27 -0500, David Bolen <db3l at fitlinxx.com> wrote:
>philh at comuno.freeserve.co.uk (phil hunt) writes:
>
>> 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.
>
>I'm not so sure.  Doing it that way presumes that in fact you aren't
>making an error while trying to access an index (word) that doesn't
>exist.

Correct. IMO "try to do something sensible" should be the default.

If the programmer *wants* to do it the other way round, that is easy 
enough to code:

   if word not in fred: 
      raise SomeException
   fred[word] ++

But 9 times out of 10, you'll want to use a default of 0.

>Python requires marginally more effort to cover this case (e.g., you
>have to explicitly use a method like .get to include a default value
>if you know the key might not yet be present), but that also means
>that the code explicitly highlights that the scenario is anticipated
>and being handled.

Having to explicitly state things like this is a sign of low 
levelnmess in a lang. Next you'll be arguing that explicit storage 
management is a good thing.... :-)

>Sure, in a simple example like an increment operation it seems a bit
>much, but as a general case, I think it's the smarter and more
>maintainable default behavior.

I have never had maintainability problems with the other way round.

-- 
<"><"><"> Philip Hunt <philh at comuno.freeserve.co.uk> <"><"><">
"I would guess that he really believes whatever is politically 
advantageous for him to believe." 
                        -- Alison Brooks, referring to Michael
                              Portillo, on soc.history.what-if



More information about the Python-list mailing list