Python (Scripting) - Convert a string to a dictionary using ast
by
Jeremy Canfield |
Updated: March 21 2024
| Python (Scripting) articles
Here is an example of how you can convert a string to a dictionary using ast.
#!/usr/bin/python3
import ast
var1 = '{"foo":"Hello", "bar":"World"}'
print(f"var1 {type(var1)}")
var2 = ast.literal_eval(var1)
print(f"var2 {type(var2)}")
Running this script should return the following because var1 is indeed a string since it's wrapped in double quotes and using ast we were able to convert the string into a dictionary.
var1 <class 'str'>
var2 <class 'dict'>
Did you find this article helpful?
If so, consider buying me a coffee over at