How to efficently build a nested dictionary

Carsten Gaebler cgaebler at gmx.de
Sat Mar 10 07:38:26 EST 2001


Hi there!

I wrote a script for FTP traffic accounting, i.e. for each "top level"
FTP directory it counts the bytes transferred per day. The traffic is
stored in a dictionary that has the following structure:

traffic = {dir: {year: {month: {day: 42}}}}

for several dirs, years, months, days, of course.

While parsing the FTP log files I am building up the dictionary in this
way:

if not traffic.has_key(dir):
    traffic[dir] = {year: {month: {day: bytes}}}
elif not traffic[dir].has_key(year):
    traffic[dir][year] = {month: {day: bytes}}
elif not traffic[dir][year].has_key(month):
    traffic[dir][year][month] = {day: bytes}
elif not traffic[dir][year][month].has_key(day):
    traffic[dir][year][month][day] = bytes
else:
    traffic[dir][year][month][day] += bytes


Now, this looks a bit clumsy to me, especially if I consider
you-know-which-language-I-mean which would simply allow to write
$traffic{$year}{$month}{$day} += $bytes;

Any ideas how to do this more elegantly?

Regards
Carsten.



More information about the Python-list mailing list