How to convert the string representation of a dictionary to a dictionary in python?

PythonServer Side ProgrammingProgramming

We can use ast.literal_eval() here to evaluate the string as a python expression. It safely evaluates 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. For example:

s = "{'baz' : 'lol', 'foo' : 'bar'}"
import ast
s = ast.literal_eval(s)
print s['foo'], s['baz']

This will give us the output:

bar lol

Dictionaries can also be seen as JSON strings. Thus we can use the json module to convert a string to dict as well. For example,

>>> import json
>>> x = json.loads("{'foo' : 'bar', 'hello' : 'world'}")
>>> type(x)
<type 'dict'>
raja
Published on 12-Dec-2017 17:59:41
Advertisements