Parsing a string into a dict
Where do you get this line from? Is it in JSON format? or python dictionary format? or just some ad-hoc format that looks like python dictionaries?
If it is JSON or if it is just a dict and only contains strings and / or numbers, you can use json.loads
, this is the safest option as it simply cannot parse the Python code.
This approach has some drawbacks though if, for example, strings are enclosed in single quotes '
instead of double quotes "
, not to mention that it only parses json objects / arrays that accidentally match similar syntax to pythons dicts / array.
Though I think that probably the string you are getting is for JSON format. I am making this assumption because it is a common data exchange format.
source to share