[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.python

Re: Automatically Writing a Dictionary

Tim Chase

1/23/2008 7:38:00 PM

> 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