How to efficently build a nested dictionary

Alex Martelli aleaxit at yahoo.com
Sat Mar 10 15:16:33 EST 2001


"Carsten Gaebler" <cg at schlund.de> wrote in message
news:3AAA7188.266516E9 at schlund.de...
> 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?
    [snip]
> > ky = (dir, year, month, day)
> > p_ttl = traffic.get(key,0)
> > traffic[ky] = p_ttl + bytes
    [snip]
> > > 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}}
    [snip]

You can sort the tuple keys of the non-nested dictionary,
then loop over the sorted keys to accumulate traffic
totals -- it's not very different from working with the
nested version.


Alex






More information about the Python-list mailing list