newbie question: how to read back the dictionary from a file?
Alex Martelli
aleax at mac.com
Mon Apr 16 10:51:19 EDT 2007
lancered <wangday at gmail.com> wrote:
> Hi Dear all,
>
> I have some data here in the form of a dictionary, called "vdic". Then
> I write them to a data file "f" using the write function as
> f.write(str(vdic)). The keys of this dictionary are integers and
> values are float numbers. Something like this:
>
> { 1: 0.00951486513347, 2: 0.0388123556019, ... ...}
>
> Now, I want to read these data back in another function. Of course, I
> could parse the string little by little, e.g, first read a "{", then
> loop read a int, then read a ":", then a float etc etc... Since it is
> written out with standard python builtin functions, I guess there may
> be some more direct method than this, say a function in some modules?
> Could someone give me a hint?
Others have suggested better ways of writing the file out. However,
it's possible to recover the data from the string form you've written,
via the eval builtin function -- with all sorts of caveats (won't be as
fast as other approaches, enormous security risk if anybody could have
tampered with the file, etc).
To mitigate the security risks a little, try
eval(thestr, dict(__builtins__={}))
or more advanced approaches such as discussed at
<http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/364469>,
<http://mail.python.org/pipermail/python-list/2006-June/390979.html>
etc.
Alex
More information about the Python-list
mailing list