How to efficently build a nested dictionary

Carel Fellinger cfelling at iae.nl
Sat Mar 10 11:33:27 EST 2001


Carsten Gaebler <cgaebler at gmx.de> wrote:
> 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}}}}

Wouldn't it be more efficient if you would build it like this:

   traffic[dir,year,month,day] = traffic.get((dir,year,month,day), 0) + bytes

or use newer Python goodies like:

   m = traffic.setdefault(dir,{}).setdefault(year,{}).setdefault(month,{})
   m[day] = m[day] + bytes

or use intermediates like:

   if traffic.has_key(dir):
      d = traffic[dir]
   else:
      d = traffic{dir] = {}
   if d.has_key(year):
      y = d[year]
   else:
      y = d[year] = {}
   if y.has_key(month):
      m = y[month]
   else:
      m = y[month] = {}
   m[day] = m[day] + bytes

or use the sometimes more efficient try-except:

   try:
      d = traffic[dir]
   except:
      d = traffic[dir] = {}

   try:
      y = d[year]
   except:
      y = d[year] = {}

   try:
      m = y[month]
   except:
      m = y[month] = {}
   
   m[day] = m[day] + bytes
   
-- 
groetjes, carel
-- 
groetjes, carel



More information about the Python-list mailing list