Newbie with sort text file question

Bengt Richter bokr at oz.net
Mon Jul 14 14:54:01 EDT 2003


On Mon, 14 Jul 2003 07:10:39 -0600, Bob Gailer <bgailer at alum.rpi.edu> wrote:
[...]
>>
>>Here's a handy idiom for what you want
>>
>>       fruits[fruit] = fruits.get(fruit, 0) + 1
>
>Don't you want setdefault() instead of get()?
>
In this case that would set the original value twice, once on either side of the '='.
Setdefault is more useful when you are maintaining a mutable, such as a list of things
that you append to, as the key's associated value. You could use a length-1 list here,
(initialized by the default to hold the count starting value of 0), e.g.,

         fruits.setdefault(fruit,[0])[0]+=1

and then later retrieve the actual count as

         fruits[fruit][0]

Regards,
Bengt Richter




More information about the Python-list mailing list