Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

String to Dictionary conversion in python

1,657 views
Skip to first unread message

santosh.y...@gmail.com

unread,
Sep 15, 2017, 2:01:46 AM9/15/17
to
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

Bill

unread,
Sep 15, 2017, 2:14:57 AM9/15/17
to
I'm new to Python too, but it looks like you need to "split" it about
the commas. Right?

Ian Kelly

unread,
Sep 15, 2017, 2:33:56 AM9/15/17
to
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'}

jlad...@itu.edu

unread,
Sep 15, 2017, 4:34:39 PM9/15/17
to
On Thursday, September 14, 2017 at 11:33:56 PM UTC-7, Ian wrote:
Very clever! And definitely not an answer that would be acceptable for a homework assignment.

Rustom Mody

unread,
Sep 15, 2017, 9:29:48 PM9/15/17
to
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
😇

Piet van Oostrum

unread,
Sep 16, 2017, 5:42:43 AM9/16/17
to
Rustom Mody <rusto...@gmail.com> writes:

> On Saturday, September 16, 2017 at 2:04:39 AM UTC+5:30, jlad...@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 <pie...@vanoostrum.org>
WWW: http://piet.vanoostrum.org/
PGP key: [8DAE142BE17999C4]

Steve D'Aprano

unread,
Sep 16, 2017, 8:37:55 AM9/16/17
to
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.

Robert L.

unread,
Sep 19, 2017, 6:21:34 PM9/19/17
to
On 9/15/2017, santosh.y...@gmail.com wrote:

> I need to convert string to dictionary
>
> string = " 'msisdn': '7382432382', 'action': 'select', 'sessionId': '123',
> 'recipient': '7382432382', 'language': 'english'"


string = " 'msisdn': '7382432382', 'action': 'select', 'sessionId': '123',
'recipient': '7382432382', 'language': 'english'"

Hash[*string.scan(/'(.*?)'/).flatten]
==>{"msisdn"=>"7382432382", "action"=>"select", "sessionId"=>"123",
"recipient"=>"7382432382", "language"=>"english"}


--
Black Panther Quanell X ... blamed the 11-year-old girl for being raped by 28
black males. http://archive.org/details/DavidDuke_videos/ (Trayvon Martin)
What I would most desire would be the separation of the white and black
races. --- A. Lincoln, July 17, 1858

sohca...@gmail.com

unread,
Sep 19, 2017, 7:07:18 PM9/19/17
to
We're not going to do your homework for you. What have you tried? What errors are you getting? If you're replying with your code or an error, make sure to use Copy/Paste and DO NOT just manually re-type the code or error. Also, make sure to post the entire traceback.

If literal_eval is out of the question, take a look at the str.split() function. I'd split on a comma, then for each result, split on the colon, then strip out the single quotes.

The actual coding of that is an exercise for the reader.
0 new messages