ast.literal_eval parses abstract syntax trees. You almost have json for which you can use json.loads , but you need double quotes, not single quotes, so that the dictionary keys are valid.
import ast result = ast.literal_eval("{'a': 1, 'b': 2}") assert type(result) is dict result = ast.literal_eval("[1, 2, 3]") assert type(result) is list
As a plus, this is not at risk of eval , as it is not part of the function evaluation business. eval("subprocess.call(['sudo', 'rm', '-rf', '/'])") can delete your root directory, but ast.literal_eval("subprocess.call(['sudo', 'rm', '-rf', '/'])") unpredictable, and your file system is not damaged.
source share