String to Dictionary conversion in python
Piet van Oostrum
piet-l at vanoostrum.org
Sat Sep 16 05:42:13 EDT 2017
Rustom Mody <rustompmody at gmail.com> writes:
> On Saturday, September 16, 2017 at 2:04:39 AM UTC+5:30, jlad... at itu.edu wrote:
> 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
>
You can catch the exception and print a nice error message:
from ast import literal_eval
def literal(s):
try:
return literal_eval('{'+s+'}')
except Exception as e:
print "%s: %s" % (type(e).__name__, ', '.join(e.args))
>>> literal("'x':1")
{'x': 1}
>>> literal("x:1")
ValueError: malformed string
But in non-interactive use you probably want to propagate the exception.
--
Piet van Oostrum <piet-l at vanoostrum.org>
WWW: http://piet.vanoostrum.org/
PGP key: [8DAE142BE17999C4]
More information about the Python-list
mailing list