[Tutor] dictionary entries within dictionary

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Tue Apr 8 14:54:01 2003


On Tue, 8 Apr 2003, Paul Tremblay wrote:

> On Mon, Apr 07, 2003 at 07:06:43PM -0700, Jeff Shannon wrote:
> > It might help to think of your nested dictionaries as a tree.  Each item
> > that's another dictionary is a twig, and items within the
> > most-deeply-nested dictionaries (such as your att:value pair) are
> > leaves.  (Try sketching out the structure, like you'd see for a family
> > tree.)  Assignment, like your original code tries to do, can only create
> > new leaves, not new twigs.  You have to build those twigs before you can
> > add leaves to them.  (To stick with the family tree example, you need to
> > create children before those new children can have grandchildren...)
>
> Thanks. This makes sense.
>
> Using nested dictionaries is very tricky. I have to extract something
> from the big dictionary to make a temporary dictionary, then make a
> smaller dictionary to add to that, and finally add the whole thing to
> the permanent dictionary. It is too bad one can't directly assign
> values, as I was trying to do.

Hi Paul,

We may want to try the setdefault() method of a dictionary; it provides
for the same kind of convenience as the "autovivifying" feature in Perl:

###
>>> d = {}
>>> d.setdefault('a', {}).setdefault('alpha', {})[0] = 1
>>> d
{'a': {'alpha': {0: 1}}}
>>> d.setdefault('a', {}).setdefault('beta', {})[0] = 42
>>> d
{'a': {'alpha': {0: 1}, 'beta': {0: 42}}}
###



That being said, doing this sort of nested dictionary by hand might not be
the best way to organize our data --- it's forcing us to think about
dictionaries within dictionaries.  And while it might be easy to
construct, it's difficult to read.  Using some sort of class structure
might be a better way to make this more palatable.


Hope this helps!