How to make tree of dictionaries?
Aahz
aahz at pythoncraft.com
Tue Aug 12 22:55:45 EDT 2003
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;
> }
>}
>
>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
--
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