2

I have a string output which is in form of a dict ex.

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

how can make easily save it as a dict and not as a string?

unutbu
887k197 gold badges1.9k silver badges1.7k bronze badges
asked Oct 18, 2009 at 16:12
3
  • This was answered quite well in previous question 988228 Commented Oct 18, 2009 at 16:56
  • What? Why not save the dict as a dict instead of creating a string in the first place? Please provide some more context on this. The question makes very little sense and indicated far larger and deeper problems may have lead to this. Commented Oct 18, 2009 at 19:59
  • 3
    As pointed out by Dave, stackoverflow.com/questions/988228/… is an exact duplicate of this Commented Oct 18, 2009 at 23:56

4 Answers 4

9

astr is a string which is "in the form of a dict". ast.literal_eval converts it to a 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'}
answered Oct 18, 2009 at 16:16
Sign up to request clarification or add additional context in comments.

1 Comment

Note that this using eval is not such a good idea if there's any way astr can contain, say, os.remove("foo").
4

This is best if you're on Python 2.6+, as it's not subject to the security holes in eval.

import ast
s = """{'key1':'value1','key2':'value2'}"""
d = ast.literal_eval(s)
dbr
171k70 gold badges284 silver badges349 bronze badges
answered Oct 18, 2009 at 22:57

1 Comment

You messed up the quotes. Use double quotes for the outside ones.
2

Where are you getting this string from? Is it in JSON format? or python dictionary format? or just some ad-hoc format that happens to be similar to python dictionaries?

If it's JSON, or if it's only a dict, and only contains strings and/or numbers, you can use json.loads, it's the most safe option as it simply can't parse python code.

This approach has some shortcomings though, if for instance, the strings are enclosed in single quotes ' instead of double quotes ", not to mention that it only parses json objects/arrays, which only coincidentally happen to share similar syntax with pythons dicts/arrays.

Though I think it's likely the string you're getting is intended to be in JSON format. I make this assumption because it's a common format for data exchange.

answered Oct 19, 2009 at 1:38

Comments

1

using json.loads - may be faster

answered Oct 18, 2009 at 22:27

1 Comment

json.loads works well for parsing JSON, but Python dictionary syntax is not quite the same. Even if you only handle simple cases, one difference is that JSON strings have to be "" quoted, while Python allows '' quotes, as in the example given.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.