Re: File to dict



mrkafk@xxxxxxxxx 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]
.



Relevant Pages

  • Re: and [True,True] --> [True, True]?????
    ... that the argument is a sequence. ... Maybe I was just too annoyed by lots of Python code I read that looked ... def foo: ... x could be a set, a dict, an unsorted list, a sorted list, a tuple, a ...
    (comp.lang.python)
  • Re: Behaviour of enumerated types
    ... with no built-in dict or sequence types. ... use enumerate(). ... the enum object itself can be used directly as an iterable. ...
    (comp.lang.python)
  • Re: Question about consistency in python language
    ... If you want to start with an empty dict ... the dict constructor will accept a sequence of pairs (so long as the first ... from a mutating method is that it is too easy to think of it ...
    (comp.lang.python)
  • Re: preferring [] or () in list of error codes?
    ... not be a class ) or a dict. ... sequence has a specific meaning beyond its mere sequential position. ...
    (comp.lang.python)
  • Re: validate string is valid maths
    ... they're the two earliest valid symbols. ... def repl_middle: ... dict return different sequences of key,value pairs or wether I'll be ... getting the same sequence each time even though they are ...
    (comp.lang.python)