How to make tree of dictionaries?

Michael Peuser mpeuser at web.de
Wed Aug 13 03:52:45 EDT 2003


"Aahz" <aahz at pythoncraft.com> schrieb im Newsbeitrag
news:bhc9bh$lp9$1 at panix1.panix.com...
> In article <87fzk6tuoq.fsf at big.terem>, Vlad Sirenko  <zcoder at bigmir.net>
wrote:
> >I need:
> >dict = {2002 : {'Jan': {1 : 'num1', 2: 'num2', 3 : 'num3'},
> >               {'Feb': {1 : 'num4', 2: 'num5', 3 : 'num6'} } }
> >        2003 : {'Jan': {1 : 'num7', 2: 'num8', 3 : 'num9'} } }
> >
> >How to do it programmatically?
> >In Perl I would do something like:
> >
> >while ($line = <>) {
> >  if ($line =~
/^---\s+\w+\s+(\w+)\s+(\d*)\s+(\d+):(\d+):(\d+)\s+(\d+)\s+---$/) {
> > ($month,$date,$hour,$minute,$sec,$year) = ($1,$2,$3,$4,$5,$6);
> > $statistics->{$year}->{$month}->{$date} += $sec;
> >  }
> >}


This is what I love Perl for!
BTW: Do you really mean += ?
This does nor match yourt example, neither seems to make much sense. Perhaps
a misconception?

> >
> >But how to do it in Python without catching 'KeyError' exception or
> >iterating over some nested loops. How to do it elegantly?
>
> You don't need nested loops, but you do need multiple statements:
>
>     tmp_year = stats.setdefault(year, {})
>     tmp_month = tmp_year.setdefault(month, {})
>     tmp_month[date] = tmp_month.setdefault(date, 0) + sec

*I* think this is less readable than the Python expression!
Note that *get* and *setdefault* are most powerful operations on mapping
types
once you get used to them, that is... ;)

Kindly
Michael P

> --
> Aahz (aahz at pythoncraft.com)           <*>
http://www.pythoncraft.com/
>
> This is Python.  We don't care much about theory, except where it
intersects
> with useful practice.  --Aahz






More information about the Python-list mailing list