Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (16.4k points)

Hello, all. Can anyone tell me how to convert the representation of str of a dict into a dict(dictionary)?

s = "{'muffin' : 'lolz', 'foo' : 'kitty'}"

Instead of using eval, what can I use?

1 Answer

0 votes
by (26.4k points)

In case of python 2.6, you can utilize ast.literal_eval (built-in function):

>>> import ast

>>> ast.literal_eval("{'muffin' : 'lolz', 'foo' : 'kitty'}")

{'muffin': 'lolz', 'foo': 'kitty'}

Actually this is much safer tha eval. Look at the following details:

>>> help(ast.literal_eval)

Help on function literal_eval in module ast:

literal_eval(node_or_string)

    Safely evaluate an expression node or a string containing a Python

    expression.  The string or node provided may only consist of the following

    Python literal structures: strings, numbers, tuples, lists, dicts, booleans,

    and None. 

Example:

>>> eval("shutil.rmtree('mongo')")

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

  File "<string>", line 1, in <module>

  File "/opt/Python-2.6.1/lib/python2.6/shutil.py", line 208, in rmtree

    onerror(os.listdir, path, sys.exc_info())

  File "/opt/Python-2.6.1/lib/python2.6/shutil.py", line 206, in rmtree

    names = os.listdir(path)

OSError: [Errno 2] No such file or directory: 'mongo'

>>> ast.literal_eval("shutil.rmtree('mongo')")

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

  File "/opt/Python-2.6.1/lib/python2.6/ast.py", line 68, in literal_eval

    return _convert(node_or_string)

  File "/opt/Python-2.6.1/lib/python2.6/ast.py", line 67, in _convert

    raise ValueError('malformed string')

ValueError: malformed string

Are you pretty much interested to learn python in detail? Come and join the python training course to gain more knowledge.

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Oct 10, 2019 in Python by Sammy (47.6k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...