json – Convert a python dict to a string and back

json – Convert a python dict to a string and back

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)

If your dictionary isnt 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.

json – Convert a python dict to a string and back

I use json:

import json

# convert to string
input = json.dumps({id: id })

# load to dict
my_dict = json.loads(input) 

Leave a Reply

Your email address will not be published.