Skip to content Skip to sidebar Skip to footer

Convert A Python Dict To A String And Back

I am writing a program that stores data in a dictionary object, but this data needs to be saved at some point during the program execution and loaded back into the dictionary objec

Solution 1:

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)

Solution 2:

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.

Solution 3:

I use json:

import json

# convert to stringinput = json.dumps({'id': id })

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

Solution 4:

Why not to use Python 3's inbuilt ast library's function literal_eval. It is better to use literal_eval instead of eval

importaststr_of_dict="{'key1': 'key1value', 'key2': 'key2value'}"
ast.literal_eval(str_of_dict)

will give output as actual Dictionary

{'key1': 'key1value', 'key2': 'key2value'}

And If you are asking to convert a Dictionary to a String then, How about using str() method of Python.

Suppose the dictionary is :

my_dict = {'key1': 'key1value', 'key2': 'key2value'}

And this will be done like this :

str(my_dict)

Will Print :

"{'key1': 'key1value', 'key2': 'key2value'}"

This is the easy as you like.

Solution 5:

Use the pickle module to save it to disk and load later on.

Post a Comment for "Convert A Python Dict To A String And Back"