Parsing a string into a dict

I have a line output that is in the form of a dict ex.

{'key1':'value1','key2':'value2'} 

      

how can one easily store it as a dict and not as a string?

+2


source to share


4 answers


astr is a string that is "in dict form". ast.literal_eval

converts it to python dict object.



In [110]: import ast

In [111]: astr="{'key1':'value1','key2':'value2'}"

In [113]: ast.literal_eval(astr)
Out[113]: {'key1': 'value1', 'key2': 'value2'}

      

+3


source


This is best if you are on Python 2.6+, as it is not prone to security bugs in eval.



import ast

s = """{'key1':'value1','key2':'value2'}"""
d = ast.literal_eval(s)

      

+3


source


using json.loads - might be faster

+1


source


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.

+1


source







All Articles