best practices: is collections.defaultdict my friend or not?

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Fri Mar 5 23:24:32 EST 2010


On Fri, 05 Mar 2010 17:22:14 -0800, Pete Emerson wrote:

> Why isn't the behavior of collections.defaultdict the default for a
> dict?

Why would it be?

If you look up a key in a dict:

addressbook['Barney Rubble']

and you don't actually have Barney's address, should Python guess and 
make something up?

In general, looking up a missing key is an error, and errors should never 
pass silently unless explicitly silenced.

And for those cases where missing keys are not errors, you're spoiled for 
choice:

dict.get
dict.setdefault
collections.defaultdict

try:
    dict[key]
except KeyError:
    do something else

Or even:

if key in dict:
    dict[key]
else:
    do something else




-- 
Steven



More information about the Python-list mailing list