Convert a text file content to a dictionary...

Alex Martelli aleax at aleax.it
Tue Feb 4 05:25:40 EST 2003


Tyler Eaves wrote:
   ...
> If you mean, as I see most likely, that you want the first column to be
> the key, and the second the value, the below willt work.

Yes, it will work, sort of -- but, don't use built-in names such as file 
and dict for variables -- one day it will bite you with some strange bug.


> import string
> file = open('yourfile','r')
> dict = {}
> for l in file.readlines():
>     d = string.split(string.strip(l))
>     dict[d[0]] = d[1]

This doesn't use tab as the delimiter, and mangles spaces in a way the
original poster didn't request.  I'd rather suggest:

d = dict([ line[:-1].split('\t') for line in file('yourfile') ])

this assumes the \n at the end of each line is best discarded,
and each line has exactly 2 fields separated by one tab -- which
is how I read the OP's specifications.

(Of course, this WILL go boom if you have rebound identifiers
dict and/or file for some purpose of your own...!).


Alex





More information about the Python-list mailing list