You can reach both goals (dict to string and string to dict without using the json lib).
Let's look at the above example:
import ast
di = {"a":2, "b": 3}
print (str(di))
>>> "{'a': 2, 'b': 3}"
print (type(str(di)))
>>> <class 'str'>
print (ast.literal_eval(str(di)))
>>> {'a': 2, 'b': 3}
print (type(ast.literal_eval(str(di))))
>>> <class 'dict'>
You have a dictionary, In order to turn it into string, you just need to cast it into str
.
If you want to return the str to dict you can use the ast
lib.
You can read more about ast.literal_eval
ast.literal_eval(node_or_string)
Safely evaluate an expression node or a Unicode or Latin-1 encoded string containing a Python literal or container display.
EDIT:
After further investigation and following this SO question It seems that using json would get you to a faster results (performance).
Look at abarnert answer at the attached link, specifacally on:
Why is json.loads so much faster ?
Because Python literal syntax is a
more complex and powerful language than JSON, it's likely to be slower
to parse. And, probably more importantly, because Python literal
syntax is not intended to be used as a data interchange format (in
fact, it's specifically not supposed to be used for that), nobody is
likely to put much effort into making it fast for data interchange.
import json
di = {"a":2, "b": 3}
print (json.dumps(di))
>>> '{"a": 2, "b": 3}'
print (type(json.dumps(di)))
>>> <class 'str'>
print (json.loads(json.dumps(di)))
>>> {'a': 2, 'b': 3}
print (type(json.loads(json.dumps(di))))
>>> <class 'dict'>