Convert String to Dictionary question

Jeff Shannon jeff at ccvcorp.com
Thu Feb 14 17:19:49 EST 2002


Gustavo Cordova wrote:

> >
> > I saved my dictionary {'hello1': [1, 0, 0]} to a file.
> >
> > When I do a readline the I get back a string.
> >
> > How do I convert this string to a dictionary?
> >
> > Thanks.
> >
>
> You eval() it?
>
> >>> d = { "one":1, "two":2, "three":3 }
> >>> print d
> {'three': 3, 'two': 2, 'one': 1}
> >>> S = str(d)
> >>> print S
> {'three': 3, 'two': 2, 'one': 1}
> >>> dd = eval(S)
> >>> print dd
> {'one': 1, 'three': 3, 'two': 2}
> >>> d is dd
> 0
> >>>

This works, but is generally a Bad Idea(tm).  The problem
with eval/exec on arbitrary strings (and any string you read
in from a file is arbitrary) is that it's hard to be
positive that what you're eval/exec-ing is what you expect.
And if it's *not*, then many, many very bad things can
happen.  (Imagine someone "accidentally" replacing that
textfile with one that contains the line "import
os;os.system('rm -s /')" -- suddenly your entire filesystem
is blank....)

If you want to store the contents of a dictionary on a
permanent disk file, you should look at the Pickle and
Shelve modules.  If you're doing this a lot, or with lots of
data, then try using one of the generic db modules (anydbm,
bsddb, etc).

Jeff Shannon
Technician/Programmer
Credit International





More information about the Python-list mailing list