Keeping track of things with dictionaries
Frank Millman
frank at chagford.com
Tue Apr 8 03:14:39 EDT 2014
"Chris Angelico" <rosuav at gmail.com> wrote in message
news:CAPTjJmqFBt2XX+BDfNHz0gaGOrDkhtpBzrR29DUWN36girzcSw at mail.gmail.com...
> On Tue, Apr 8, 2014 at 2:02 PM, Josh English <Joshua.R.English at gmail.com>
> wrote:
>>
>> Would dict.setdefault() solve this problem? Is there any advantage to
>> defaultdict over setdefault()
>
> That depends on whether calling Brand() unnecessarily is a problem.
> Using setdefault() is handy when you're working with a simple list or
> something, but if calling Brand() is costly, or (worse) if it has side
> effects that you don't want, then you need to use a defaultdict.
>
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?
Frank Millman
More information about the Python-list
mailing list