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.
>
>>>> def get_value(val):
> ...   print('getting value', val)
> ...   return val*2
> ...
>>>> my_dict = {}
>>>> my_dict.setdefault('a', get_value('xyz'))
> getting value xyz
> 'xyzxyz'
>>>> my_dict.setdefault('a', get_value('abc'))
> getting value abc
> 'xyzxyz'
>>>> my_dict
> {'a': 'xyzxyz'}
>>>>
>
> 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.)

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list

Reply via email to