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

Chris Kaynor ckaynor at zindagigames.com
Sat Mar 6 03:20:42 CET 2010


On Fri, Mar 5, 2010 at 5:22 PM, 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'
> >>> data['one'] = {}
> >>> data['one']['two'] = 'three'
> >>> print data
> {'one': {'two': 'three'}}
>
>
Perhaps a better idiom for what you are doing would be to use tuples as the
keys: (I don't have a handy Python interpreter, so untested)
data = {}
data[('one', 'two')] = 'three'
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20100305/ec1ed349/attachment.html>


More information about the Python-list mailing list