String to Dictionary conversion in python

Rustom Mody rustompmody at gmail.com
Fri Sep 15 21:29:20 EDT 2017


On Saturday, September 16, 2017 at 2:04:39 AM UTC+5:30, jlad... at itu.edu wrote:
> On Thursday, September 14, 2017 at 11:33:56 PM UTC-7, Ian wrote:
> > On Fri, Sep 15, 2017 at 12:01 AM,  <s... at g...com> wrote:
> > > Hi,
> > >
> > > Can anyone help me in the below issue.
> > >
> > > I need to convert string to dictionary
> > >
> > > string = " 'msisdn': '7382432382', 'action': 'select', 'sessionId': '123', 'recipient': '7382432382', 'language': 'english'"
> > >
> > > Can anyone help me with the code
> > 
> > It looks like this might do what you need:
> > 
> > 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


>>> literal_eval("'x':1")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/ast.py", line 49, in literal_eval
    node_or_string = parse(node_or_string, mode='eval')
  File "/usr/lib/python2.7/ast.py", line 37, in parse
    return compile(source, filename, mode, PyCF_ONLY_AST)
  File "<unknown>", line 1
    'x':1
       ^
SyntaxError: invalid syntax




> And definitely not an answer that would be acceptable for a homework assignment.

😇



More information about the Python-list mailing list