I have been trying to convert a string of dictionary objects as given below
"{'Cmd': None, 'Hostname': None, 'Entrypoint': None, 'Env': None, 'OpenStdin': False,
'Tty': False, 'Domainname': None, 'Image': u'nginx:latest', 'HostConfig':
{'Binds': None, 'RestartPolicy': {}, 'NetworkMode': u'bridge', 'Dns': None,
'Links': [], 'PortBindings': {}, 'DnsSearch': None, 'Privileged': False,
'VolumesFrom': []}, 'ExposedPorts': {}, 'User': None}"
to python dictionary.
But the solutions came up while searching were suggesting to use python ast library for the purpose. as
import ast
ast.literal_eval(string)
And it works fine. But is ast library is built indented to solve problems like this ? Is there any good approach other than this to solve the problem ?
2 Answers 2
To answer your question, yes ast
is ok to be used for this. Per the documentation for literal_eval
:
Safely evaluate an expression node or a Unicode or Latin-1 encoded string containing a Python literal or container display. The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None.
This can be used for safely evaluating strings containing Python values from untrusted sources without the need to parse the values oneself. It is not capable of evaluating arbitrarily complex expressions, for example involving operators or indexing.
Yes. Whenever you are choosing libraries, make sure that the libraries are not only comfortable with IPython consoles like Jupyter, but also habituated to the Python shell.
Hence it is easier to use YAML:
import yaml
s= #your string supposed to be
your_dict=yaml.load(s)
json
, but your string is not quite valid JSON (None
instead ofnull
, etc.) -- if it were, you could simply usejson.loads
from the Python standard library. \$\endgroup\$