[Tutor] re: turn a file into a dictionary

Charlie Clark charlie@begeistert.org
Sun, 29 Sep 2002 12:29:07 +0000


On 2002-09-29 at 09:38:02 [+0000], you wrote:
> {user1:tab3,tab5}
> {User2:tab1,tab2,tab3,tab4,tab5}
> 
> with the intent of simply writing:
> 
> f=3Dopen('C:\Other\Prg\ACL.CSV','r')
> dict=3Df.readlines()
> 
> Regrettably, this turns each record into a string, rather than a
> dictionary entry. My question, then, is: do I need to readline() records
> one by each, parsing the resulting string into a key:(list) sort of form
> or is there a more pythonic way of doing it as a single operation? I
> don't mind record level processing where it's absolutely necessary, but
> if it can be avoided, I find the result cleaner and easier to read.
> 
> Any advice or links where I can RTFM will be valued.

Magnus has already answered the question but I thought I'd mention a couple=
 
of alternatives.

First of all, as Magnus points out, you could do:

myFileText =3D file(filename).read()
d =3D eval("{ %s }" % myFileText)

He advises you against this - the reason being that 'eval' won't do any 
security checking. It's conceivable, therefore, that your file contains 
some text will might be dangerous when run as Python code. This kind of 
security risk is common to all programming languages notably cgi and SQL.

What do you want to do with your file? ie. how do you want to manage data 
in the future: by direct manipulation of the textfile in a text editor or 
through your program? If you still need to edit the textfile you're best 
following Magnus' suggestion. If not you will might consider using the 
pickle or shelve module to store your data and thus avoid the overhead of 
converting from string to dictionary and back again. Pickle and shelve use 
textfiles to store binary data such as dictionaries. Pickle is a generic 
tool for storing all kinds of Python objects in textfiles whereas shelve is=
 
specifically for dictionaries. You can edit the textfiles thus created if 
you are really careful but it's not advisable. XML-Pickle may give you the 
best of both worlds allowing you to manage your data either in a text 
editor or in a program.

Charlie
-- 
Charlie Clark
Helmholtzstr. 20
D=1Asseldorf
D- 40215
Tel: +49-211-938-5360
GSM: +49-178-782-6226