Keeping track of things with dictionaries

Chris Angelico rosuav at gmail.com
Tue Apr 8 00:08:23 EDT 2014


On Tue, Apr 8, 2014 at 2:02 PM, Josh English <Joshua.R.English at gmail.com> wrote:
> On Sunday, April 6, 2014 12:44:13 AM UTC-7, Giuliano Bertoletti wrote:
>
>
>> obj = brands_seen.get(brandname)
>>
>> if obj is None:
>>     obj = Brand()
>>     brands_seen[brandname] = obj
>>
>>
>
> 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.

I think this is a textbook example of why defaultdict exists, though,
so I'd be inclined to just use it, rather than going for setdefault :)

ChrisA



More information about the Python-list mailing list