patternpythonMinor
Converting string to dict using Python ast library
Viewed 0 times
dictastusingpythonlibraryconvertingstring
Problem
I have been trying to convert a string of dictionary objects as given below
to python dictionary.
But the solutions came up while searching were suggesting to use python ast library for the purpose. as
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 ?
"{'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 ?
Solution
To answer your question, yes
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.
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.
Context
StackExchange Code Review Q#106719, answer score: 5
Revisions (0)
No revisions yet.