parsing a dictionary from a string

Tim Williams tim at tdw.net
Fri Dec 15 13:12:03 EST 2006


On 15/12/06, Benjamin Georgi <georgi at molgen.mpg.de> wrote:
> Hello list,
>
> I could use some help extracting the keys/values of a list of
> dictionaries from a string that is just the str() representation of the
> list (the problem is related to some flat file format I'm using for file
> IO).
>
> Example:
>  >>> s = str(dict_list)
>  >>> s
> '[{0: [2], 1: []}, {0: [], 1: [], 2: []}, {0: [1, 2]}]'
>
> Then, what I want to do is to reconstruct dict_list given s.
> Now, one possible solution would be
>
>  >>> dict_list = eval(s)
>
> but since the content of s cannot be blindly trusted I`d rather not do
> it that way. Basically my question is whether there is another solution
> which is simpler than using regular expressions.


I'm sure I'll get flamed for the following !!  LOL

You could check that the string contains at least part of what you are
expecting.

if  s[0] == '[' :    dict_list = eval(s)

or
if  s[:2] == '[{' :   dict_list = eval(s)
if  s[:2] == '[{' and  s[-2:] == '}]' :  dict_list = eval(s)
etc

I doubt it is perfect,  but it is quick and simple and much safer than
a straight eval()

*or*

try:
    dict_list = [eval(x+'}') for x in
s.replace('[{','{').replace('}]','').split('},')]
except:
    print "file may be compromised"



More information about the Python-list mailing list