"Chris Angelico" <ros...@gmail.com> wrote in message news:captjjmpk-rqx0fp6_4vxyus2z34vc5fq_qntj+q9+kn8y5u...@mail.gmail.com... > On Tue, Apr 8, 2014 at 5:14 PM, Frank Millman <fr...@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 -- https://mail.python.org/mailman/listinfo/python-list