How to convert a string dictionary to a Python dictionary?

I have the following line, which is a Python string dictionary:

some_string = '{123: False, 456: True, 789: False}' 

How to get Python dictionary from above line?

+4
source share
3 answers

Well you can do

 d = eval(some_string) 

But if the string contains user input, this is a bad idea, because there might be some random malicious function in the expression. See Python Security 'eval' for Deserializing a List

Thus, a safer alternative might be:

 import ast d = ast.literal_eval(some_string) 

From http://docs.python.org/library/ast.html#ast.literal_eval :

A given string or node can only consist of the following Python literary structures: strings, numbers, tuples, lists, dicts, booleans, and None.

+7
source

Use ast.literal_eval :

It is safe to evaluate a node expression or a string containing a Python expression. A string or node can contain only the following literary Python structures: strings, numbers, tuples, lists, dicts, booleans, and None.

This can be used to safely evaluate strings containing Python expressions from untrusted sources without having to analyze the values ​​themselves.

Example:

 >>> some_string = '{123: False, 456: True, 789: False}' >>> import ast >>> ast.literal_eval(some_string) {456: True, 123: False, 789: False} 
+11
source

The only safe way to do this is ast.literal_eval (it is safe because, unlike the built-in eval , a string is a node that can contain only the following literary Python structures: strings, numbers, tuples, lists, dicts, booleans and None . "" ".

+1
source

All Articles