Home >Backend Development >Python Tutorial >How to Safely Convert String Representations of Dictionaries to Dictionaries in Python?
Converting String Representations of Dictionaries to Dictionaries
Consider the task of converting a string representation of a dictionary into a dictionary. For example:
s = "{'muffin' : 'lolz', 'foo' : 'kitty'}"
One may be tempted to use the eval function for this purpose, but it is preferable to avoid eval due to its potential security risks.
Instead, consider using the ast.literal_eval function provided by Python's standard library:
import ast dictionary = ast.literal_eval(s)
The ast.literal_eval function safely evaluates a string containing a Python expression. It only allows literal structures such as strings, numbers, tuples, lists, dictionaries, booleans, and None, ensuring that the expression is safe to evaluate.
This method is safer than using eval, as it prevents the execution of arbitrary code that could potentially compromise your system. For example:
# Dangerous example: eval("shutil.rmtree('mongo')") # Safe example: ast.literal_eval("shutil.rmtree('mongo')")
In the first example, eval executes the string as Python code, which results in an error because mongo is not a valid directory. In the second example, ast.literal_eval safely evaluates the string as a literal expression and raises an error indicating that the string is malformed.
The above is the detailed content of How to Safely Convert String Representations of Dictionaries to Dictionaries in Python?. For more information, please follow other related articles on the PHP Chinese website!