String to Dictionary conversion in python

Steve D'Aprano steve+python at pearwood.info
Sat Sep 16 08:37:28 EDT 2017


On Sat, 16 Sep 2017 11:29 am, Rustom Mody wrote:

>> > py> import ast
>> > py> string = " 'msisdn': '7382432382', 'action': 'select',
>> > 'sessionId': '123', 'recipient': '7382432382', 'language': 'english'"
>> > py> ast.literal_eval('{%s}' % string)
>> > {'sessionId': '123', 'recipient': '7382432382', 'msisdn':
>> > '7382432382', 'action': 'select', 'language': 'english'}
>> 
>> Very clever!
> Yeah… I used to think thus
> But literal_eval has excessive crud in its error messages:
> 
>>>> from ast import literal_eval
> 
>>>> literal_eval("{'x':1}")
> {'x': 1}
> 
> Ok…
> 
>>>> literal_eval("{x:1}")
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
>   File "/usr/lib/python2.7/ast.py", line 80, in literal_eval
>     return _convert(node_or_string)
>   File "/usr/lib/python2.7/ast.py", line 63, in _convert
>     in zip(node.keys, node.values))
>   File "/usr/lib/python2.7/ast.py", line 62, in <genexpr>
>     return dict((_convert(k), _convert(v)) for k, v
>   File "/usr/lib/python2.7/ast.py", line 79, in _convert
>     raise ValueError('malformed string')
> ValueError: malformed string

Here's the bug tracker: make a feature request for literal_eval to be more
concise in its traceback and provide a more useful and detailed error message.

https://bugs.python.org/




-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.




More information about the Python-list mailing list