How to efficently build a nested dictionary

Carel Fellinger cfelling at iae.nl
Sat Mar 10 14:52:50 EST 2001


Carsten Gaebler <cg at schlund.de> wrote:
> 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?

   import operator
   vs = [traffic[D,y,m,d] for (D,y,m,d) in traffic.keys()
         if D==dir and y==year ]
   total = reduce(operator.add, vs, 0)

This has the bonus feature that it's dead easy to get strange totals,
like the total of all traffic on mondays:

   import DateTime
   vs = [traffic[D,y,m,d] for (D,y,m,d) in traffic.keys()
         if D==dir and y==year and DateTime(y,m,d).day_of_week==0 ]
   total_on_mondays = reduce(operator.add, vs, 0)
-- 
groetjes, carel



More information about the Python-list mailing list