File to dict

Duncan Booth duncan.booth at invalid.invalid
Fri Dec 7 06:59:40 EST 2007


mrkafk at gmail.com wrote:

> def lookupdmo(domain):
>         lines = open('/etc/virtual/domainowners','r').readlines()
>         lines = [ [y.lstrip().rstrip() for y in x.split(':')] for x in
> lines]
>         lines = [ x for x in lines if len(x) == 2 ]
>         d = dict()
>         for line in lines:
>                 d[line[0]]=line[1]
>         return d[domain]

Just some minor points without changing the basis of what you have done 
here:

Don't bother with 'readlines', file objects are directly iterable.
Why are you calling both lstrip and rstrip? The strip method strips 
whitespace from both ends for you.

It is usually a good idea with code like this to limit the split method to 
a single split in case there is more than one colon on the line: i.e. 
x.split(':',1)

When you have a sequence whose elements are sequences with two elements 
(which is what you have here), you can construct a dict directly from the 
sequence.

But why do you construct a dict from that input data simply to throw it 
away? If you only want 1 domain from the file just pick it out of the list. 
If you want to do multiple lookups build the dict once and keep it around.

So something like the following (untested code):

from __future__ import with_statement

def loaddomainowners(domain):
    with open('/etc/virtual/domainowners','r') as infile:
        pairs = [ line.split(':',1) for line in infile if ':' in line ]
        pairs = [ (domain.strip(), owner.strip())
            for (domain,owner) in pairs ]
        return dict(lines)

DOMAINOWNERS = loaddomainowners()

def lookupdmo(domain):
    return DOMAINOWNERS[domain]



More information about the Python-list mailing list