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

Andreas Waldenburger usenot at geekmail.INVALID
Fri Mar 5 21:10:03 EST 2010


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

> [snip]
> >>> 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'}})
> 
> [snip]
> 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.
> 

Oh, by the way: That defaultdict route is a pretty solid solution. Not
sure what problem you're trying to solve -- depending on your usecase,
there might be a better approach.

If you're just asking hypothetically and you're trying to apply a
Perl idiom to Python, there probably *is* a better solution.

/W

-- 
INVALID? DE!




More information about the Python-list mailing list