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

Andreas Waldenburger usenot at geekmail.INVALID
Fri Mar 5 21:02:58 EST 2010


On Fri, 5 Mar 2010 17:22:14 -0800 (PST) Pete Emerson
<pemerson at gmail.com> wrote:

> I've been wrestling with dicts. I hope at the very least what I
> discovered helps someone else out, but I'm interested in hearing from
> more learned python users.
> 
> I found out that adding a two dimensional element without defining
> first dimension existing doesn't work:
> 
> >>> data = {}
> >>> data['one']['two'] = 'three'
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> KeyError: 'one'
Yeah, because that key 'one' indexes what exactly?


> [snip]
> 
> And through some research, I discovered collections.defaultdict (new
> in Python 2.5, FWIW):
> 
> [snip]
> 
> Why isn't the behavior of collections.defaultdict the default for a
> dict?
Because explicit is better than implicit. How should Python know what
you want to fill your dict with? It could be anything that takes string
indices. Only two lines of code remove all the guesswork.


> Am I just revelling in my bad perl habits by not wanting to declare a
> previous level first?
Yes.

Python pretty much never guesses (not that I knew of anyway). I think
that is good, because it's just too easy to overlook some magic the
language does and spend an hour trying to understand why that Toyota
hit that wall.


> Is this sort of "more rigid" way of doing things common throughout
> python, and is it best that I not fight it, but embrace it?
> 
Seriously, what answer do you expect? ;) When has fighting a language
ever brought about something really cool. (I'm really looking forward
to the geeky humorous replies this is bound to sprout.)



> Your thoughts and comments are very much appreciated. I think my brain
> already knows some of the answers, but my heart ... well, perl and I
> go way back. Loving python so far, though.
> 
Welcome on board.

Have you typed "import this" in the command prompt yet?



-- 
INVALID? DE!




More information about the Python-list mailing list