Convert a python dict to a string and back
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Island
--
Chapters
00:00 Question
00:34 Accepted answer (Score 436)
00:53 Answer 2 (Score 249)
01:16 Answer 3 (Score 202)
01:29 Answer 4 (Score 30)
02:24 Thank you
--
Full question
https://stackoverflow.com/questions/4547...
Accepted answer links:
[The json module]: https://docs.python.org/3/library/json.h...
Answer 2 links:
[ast.literal_eval]: http://docs.python.org/library/ast.html
Answer 3 links:
[json]: https://docs.python.org/2/library/json.h...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #json #dictionary #serialization
#avk47
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Island
--
Chapters
00:00 Question
00:34 Accepted answer (Score 436)
00:53 Answer 2 (Score 249)
01:16 Answer 3 (Score 202)
01:29 Answer 4 (Score 30)
02:24 Thank you
--
Full question
https://stackoverflow.com/questions/4547...
Accepted answer links:
[The json module]: https://docs.python.org/3/library/json.h...
Answer 2 links:
[ast.literal_eval]: http://docs.python.org/library/ast.html
Answer 3 links:
[json]: https://docs.python.org/2/library/json.h...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #json #dictionary #serialization
#avk47
ACCEPTED ANSWER
Score 460
The json module is a good solution here. It has the advantages over pickle that it only produces plain text output, and is cross-platform and cross-version.
import json
json.dumps(dict)
ANSWER 2
Score 266
If your dictionary isn't too big maybe str + eval can do the work:
dict1 = {'one':1, 'two':2, 'three': {'three.1': 3.1, 'three.2': 3.2 }}
str1 = str(dict1)
dict2 = eval(str1)
print(dict1 == dict2)
You can use ast.literal_eval instead of eval for additional security if the source is untrusted.
ANSWER 3
Score 214
I use json:
import json
# convert to string
input_ = json.dumps({'id': id_ })
# load to dict
my_dict = json.loads(input_)
ANSWER 4
Score 15
Use the pickle module to save it to disk and load later on.