Convert a text file content to a dictionary...
David Eppstein
eppstein at ics.uci.edu
Mon Feb 3 20:10:10 EST 2003
In article <w4E%9.4467$vL2.1781 at tornadotest1.news.pas.earthlink.net>,
Tyler Eaves <tyler at cg1.org> 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.
>
> import string
> file = open('yourfile','r')
> dict = {}
> for l in file.readlines():
> d = string.split(string.strip(l))
> dict[d[0]] = d[1]
Or, more succinctly:
D = dict([line.strip().split('\t') for line in file])
(btw, probably bad form to call your dict dict, since that shadows the
type name...)
--
David Eppstein UC Irvine Dept. of Information & Computer Science
eppstein at ics.uci.edu http://www.ics.uci.edu/~eppstein/
More information about the Python-list
mailing list