String to Dictionary conversion in python

jladasky at itu.edu jladasky at itu.edu
Fri Sep 15 16:34:16 EDT 2017


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!  And definitely not an answer that would be acceptable for a homework assignment.



More information about the Python-list mailing list