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

Pete Emerson pemerson at gmail.com
Sat Mar 6 06:36:39 CET 2010


On Mar 5, 8:24 pm, Steven D'Aprano <st... at REMOVE-THIS-
cybersource.com.au> wrote:
> 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

My frame of reference for the past 10 < N < 15 years has been doing
this sort of assignment in perl:

$hash{key1}{key2} = value

I definitely agree that looking up a missing key should give an error.
The lazy perl programmer in me just wants to make an assignment to a
missing second key without defining the first key first. I'm not
saying it's right, I'm saying that it's something I'm trying to
unlearn, as I'm being convinced that it's the "best way" to do it in
python.

I'll take a look at dict.get and dict.setdefault, thank you for those.

I'm learning, and you're all very helpful, and I appreciate it!

Pete



More information about the Python-list mailing list