parsing a dictionary from a string

Benjamin Georgi georgi at molgen.mpg.de
Mon Dec 18 06:06:43 EST 2006


Fredrik Lundh wrote:
> Benjamin Georgi wrote:
> 
>> 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.
> 
> here are a couple of cut-and-paste alternatives:
> 
> use the tokenizer and a simple parser pattern:
> 
>    http://groups.google.com/group/comp.lang.python/msg/a34397ba74892b4e
> 
> use the compiler module and analyze the parse tree:
> 
>    http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/364469
> 
> note that you cannot parse Python's expression syntax with plain regular 
> expressions; RE's are only good enough for lexical analysis.
> 
> </F>
> 
Problem solved. Thanks to everybody who answered.

Benjamin



More information about the Python-list mailing list