This post will discuss how to convert a dictionary into a string in Python and vice versa.

1. Using pickle module

The standard solution for serializing and deserializing a Python dictionary is with the pickle module. The dumps() function serialize a Python object by converting it into a byte stream, and the loads() function do the inverse, i.e., convert the byte stream back into an object.

Download  Run Code

 
Python has a more primitive serialization module called marshal to support Python’s .pyc files. However, the pickle module should always be the preferred way to serialize Python objects.

Download  Run Code

2. Using json module

A more flexible way to do serialize and deserialize a Python object is using the json module. Unlike the pickle module, which is a binary serialization format, json module outputs human-readable Unicode text.

To serialize a dictionary, you simply call the dumps() function.

Download  Run Code

 
To deserialize a dictionary, i.e., convert serialized data back to a dictionary, call the loads() function:

Download  Run Code

3. Using ast module

Finally, for simple dictionaries, you can pass your dictionary to a string constructor str() to get a string representation of the dictionary object.

Download  Run Code

 
Then use the literal_eval() function from the ast module to safely deserialize the string containing a Python dictionary.

Download  Run Code

That’s all about converting a dictionary to a string in Python.