Convert String to Dictionary question

Jacek Generowicz jacek.generowicz at cern.ch
Fri Feb 15 03:19:05 EST 2002


Jeff Shannon <jeff at ccvcorp.com> writes:

> 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....)

Writing python scripts works but is generally a Bad Idea(tm).

Imagine somone "accidentally" replacing the textfile containing your
script with one that contains the line "import os;os.system('rm -s
/')" -- suddenly your entire filesystem is blank....)

Sic probo.

:-)



More information about the Python-list mailing list