How to efficently build a nested dictionary

Carsten Gaebler cg at schlund.de
Sat Mar 10 13:25:12 EST 2001


I'd like to be able to print out the annual, monthly or daily traffic for
each directory. With nested dictionaries I could easily accomplish this by
using nested for loops. How would I do that with a compound key?

cg.


Emile van Sebille wrote:
> 
> Any particular reason not to do:
> 
> ky = (dir, year, month, day)
> p_ttl = traffic.get(key,0)
> traffic[ky] = p_ttl + bytes
> 
> --
> 
> Emile van Sebille
> emile at fenx.com
> -------------------
> 
> "Carsten Gaebler" <cgaebler at gmx.de> wrote in message
> news:3AAA2042.E69A53FC at gmx.de...
> > 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