complex data structures in python

Chris Rebert clp2 at rebertia.com
Mon May 2 23:58:24 EDT 2011


On Mon, May 2, 2011 at 7:46 PM, Rita <rmorgan466 at gmail.com> wrote:
> Hello,
> I was wondering if anyone has any documentation/recipes for implementing
> complex data structures. For instance, if you had a dictionary with a list
> inside a list inside a set.

Er, there's no special magic. The datatypes just nest normally. Pretty
much the only thing to look out for is immutability/hashability.
Dictionary keys and set elements should typically be immutable (and
thus sensibly hashable). For this reason, tuples and frozensets are
used instead of lists and non-frozen sets (respectively) in those
situations (and in other cases where mutability should be disallowed).
When creating a custom immutable type, one should override the
__eq__(), __ne__(), and __hash__() special methods so that the type's
instances can be used as dict keys and set elements.

Your particular example combination doesn't work since it violates the
aforementioned immutability rule.

One should also be aware of the datatypes in the `collections` module,
particularly `defaultdict`:
http://docs.python.org/library/collections.html

Cheers,
Chris
--
http://rebertia.com



More information about the Python-list mailing list