How to convert a String representation of a Dictionary to a dictionary in Python?

PythonServer Side ProgrammingProgramming

Dictionary object is easily convertible to string by str() function.

>>> D1={'1':1, '2':2, '3':3}
>>> D1
{'1': 1, '2': 2, '3': 3}
>>> str(D1)
"{'1': 1, '2': 2, '3': 3}"

To convert a string to dictionary, we have to ensure that the string contains a valid representation of dictionary. This can be done by eval() function.

>>> D1={'1':1, '2':2, '3':3}
>>> s=str(D1)
>>> s
"{'1': 1, '2': 2, '3': 3}"
>>> D2=eval(s)
>>> D2
{'1': 1, '2': 2, '3': 3}

Abstract Syntax Tree (ast) module of Python has literal_eval() method which safely evaluates valid Python literal structure.

>>> D1={'1':1, '2':2, '3':3}
>>> s=str(D1)
>>> import ast
>>> D2=ast.literal_eval(s)
>>> D2
{'1': 1, '2': 2, '3': 3}

raja
Published on 30-Jan-2018 00:06:54
Advertisements