Convert a text file content to a dictionary...

Tyler Eaves tyler at cg1.org
Mon Feb 3 19:47:24 EST 2003


Meehan, Francois unleashed the following on comp.lang.python:
> 
> 
> Hi all,
> 
> I want to read a simple text file that has 2 columns (tab delimited), and
> put that content in a dictionary. What is the best way to achieve this???
> 
> Regards,
> 
> Francois
> 
That depends on you what you mean by 'put the content in a dictionary'.

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.

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

-- 
Tyler Eaves

Funadmental Python - Free Ebook!
http://cg1.org/pythontut.pdf




More information about the Python-list mailing list