Building a Tree: IMAP Mailbox list

Brian Jones bojo at example.com
Wed Oct 15 19:33:14 EDT 2003


Hello, I am trying to build a dictionary tree from a mailbox list I have
returned using the imaplib module.  This just boils down to general
inexperience, but any help would be appreciated.

I am attempting to take the following list:
boxlist = ['INBOX.save.subsave', 'INBOX.Drafts', 'INBOX.Sent', 'INBOX.save',
'INBOX.web','INBOX.Trash', 'INBOX']

And turn it into something like:

newlist = {
    'INBOX': {
        'INBOX.Drafts': None,
        'INBOX.Sent': None,
        'INBOX.save': {
            'INBOX.save.subsave': None
        },
        'INBOX.web': None,
        'INBOX.Trash': None,
    }
}

I am hoping this is just trivial, and I am on the right track.

The following is the code I have written.  It doesn't actually build the
tree however, because that is the part I am uncertain about:

################
# Code
################

import re
import string

class mailboxsort:

 nodetree = {}

 def __init__(self, list):
  self.masterlist = list

 def buildTree(self, node):
  children = self.getChildren(node)
  if len(children) > 0:
   self.lastnode = node
   for num in range(len(children)):
    child = children[num]
    self.buildTree(child)

 def getChildren(self, node):
  children = []
  for mailbox in self.masterlist:
   renode = node + '.'
   if re.compile(renode).match(mailbox):
    nodelen = len(node.split('.'))
    childlen = len(mailbox.split('.'))
    if childlen == (nodelen + 1):
     children.append(mailbox)
  return children

if __name__ == '__main__':
 boxlist = ['INBOX.save.subsave', 'INBOX.Drafts', 'INBOX.Sent',
'INBOX.save', 'INBOX.web','INBOX.Trash', 'INBOX']
 boxsort = mailboxsort(boxlist)
 boxsort.buildTree('INBOX')
 print boxsort.nodetree



Brian "bojo" Jones
bojo at gvea dot com






More information about the Python-list mailing list