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

Mark Lawrence breamoreboy at yahoo.co.uk
Sun Mar 7 10:33:22 CET 2010


Pete Emerson wrote:
> On Mar 5, 6:10 pm, Andreas Waldenburger <use... at geekmail.INVALID>
> wrote:
>> On Fri, 5 Mar 2010 17:22:14 -0800 (PST) Pete Emerson
>>
>>
>>
>>
>>
>> <pemer... 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!
> 
> I found out about the need to declare the higher level as I was
> reading in a JSON struct into a dict and then adding a new entry at a
> lower level. Mostly just proof of concept stuff as I'm learning
> python. I'm not sure that the use of defaultdict is really warranted
> for me anywhere just yet. Mostly, I don't want to convert my perl to
> python, that seems very counterproductive. Thank you very much for
> your insight.
> 
> I was a little frightened of doing "import this" ("Hey, kid, run rm -
> rf / and see what happens!"), but did, and the words are wise. :)
> 
> Pete

After reading the words of wisdom try "import this" a second time and 
watch what happens, it's quite interesting if you're not expecting the 
output.

Mark Lawrence.




More information about the Python-list mailing list