How to make tree of dictionaries?

V

Vlad Sirenko

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?
 
A

Aahz

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
 
M

Michael Peuser

Aahz said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,050
Latest member
AngelS122

Latest Threads

Top