Keeping track of things with dictionaries

Frank Millman frank at chagford.com
Tue Apr 8 04:26:27 EDT 2014


"Chris Angelico" <rosuav at gmail.com> wrote in message 
news:CAPTjJmpK-rqX0fp6_4vXYUS2Z34Vc5fQ_qNTj+Q9+Kn8Y5UPAA at mail.gmail.com...
> On Tue, Apr 8, 2014 at 5:14 PM, Frank Millman <frank at chagford.com> wrote:
>> It appears that when you use 'setdefault', the default is always 
>> evaluated,
>> even if the key exists.
>>
>> It seems odd. Is there a situation where this behaviour is useful?
>
> If the default value is cheap to define and has no side effects, it
> can be very clean.
>
> words_by_length = {}
> for word in open("/usr/share/dict/words"):
>    words_by_length.setdefault(len(word), []).append(word)
>
> This will, very conveniently, give you a list of all words of a
> particular length. (It's actually a little buggy but you get the
> idea.)
>

Thanks, that is neat.

I haven't spotted the bug yet! Can you give me a hint?

Frank






More information about the Python-list mailing list