Keeping track of things with dictionaries

Chris Angelico rosuav at gmail.com
Tue Apr 8 04:00:28 EDT 2014


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.
>
>>>> 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



More information about the Python-list mailing list