Automatically Writing a Dictionary

Tim Chase python.list at tim.thechases.com
Wed Jan 23 14:37:41 EST 2008


> input = "/usr/local/machine-lang-trans/dictionary.txt"
> 
> input = open(input,'r')
> 
> dict = "{"
> for line in input:
> ? tup = re.split(','line)
> ? dict += '"' + tup[0] +'":"' + tup[1] +'", '
> dict += "}"
> input.close()
> 
> 
> Of course, that will just give me a string. How do I convert
> it to, or make from scratch, a dictionary of that?

Don't bother with the string (and as a side-note, it's bad style 
to mask the built-in dict() so I'll use "d"):

   d = {}
   for line in input:
     key, value = line.split(',').rstrip('\n')
     d[key] = value

or even just

   d = dict(line.split(',').rstrip('\n')
            for line in input)

using the aforementioned dict() function :-)

You may want to clean it up a bit in case there are spurious 
leading/trailing spaces to be trimmed:

   from string import strip
   d = dict(map(strip, line.split(','))
            for line in input)

or even ignore lines with the wrong number of commas:

   d = dict(map(strip, line.split(','))
            for line in input
            if line.count(',') == 1)

or assume any extra commas are part of the value:

   d = dict(map(strip, line.split(',',1))
            for line in input
            if line.count(',') > 0)

HTH,

-tkc







More information about the Python-list mailing list