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

Pete Emerson pemerson at gmail.com
Sat Mar 6 00:42:37 EST 2010


On Mar 5, 6:26 pm, MRAB <pyt... at mrabarnett.plus.com> wrote:
> Pete Emerson 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'
> >>>> data['one'] = {}
> >>>> data['one']['two'] = 'three'
> >>>> print data
> > {'one': {'two': 'three'}}
>
> > And through some research, I discovered collections.defaultdict (new
> > in Python 2.5, FWIW):
>
> >>>> import collections
> >>>> data = collections.defaultdict(dict)
> >>>> data['one']['two'] = 'three'
> >>>> print data
> > defaultdict(<type 'dict'>, {'one': {'two': 'three'}})
>
> > Why isn't the behavior of collections.defaultdict the default for a
> > dict?
> > Am I just revelling in my bad perl habits by not wanting to declare a
> > previous level first?
> > 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?
>
> > 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.
>
> Someone once wrote about a case where he was porting a frontend from
> Perl to Python. It called a backend and parsed the result. Sometimes
> converting one of the fields to a number would raise a ValueError
> because it would contain "ERR" instead of a number, which Perl, of
> course, would silently convert to 0!
>
> Python is all about refusing to guess, and complaining if there's an
> error. :-)

Perl is quite an amazing language, but it also definitely allows for
sloppy habits and poor coding behaviors, particularly for someone such
as me whose perl is completely self taught. I think that's why this
time around with python I'm trying to learn my prior experience and
seek help in areas where I suspect there is improvement to be made.
I'm really liking the rigid flexibility I'm experiencing with python
so far.

I'm thinking it's time for me to get a python reference or two, just
to kill a few trees. If anyone has any strong feelings about what
belongs in a "beginner but already learning quickly" library, please
toss them my way. I'll grep around the 'net for opinions on it, too.

Pete



More information about the Python-list mailing list