Convert a dictionary to a Python string
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.
|
1 2 3 4 5 6 7 8 9 10 11 |
import pickle if __name__ == '__main__': dict = {'A': 1, 'B': 2, 'C': 3} serialized = pickle.dumps(dict) deserialized = pickle.loads(serialized) print(deserialized) # {'A': 1, 'B': 2, 'C': 3} |
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.
|
1 2 3 4 5 6 7 8 9 10 11 |
import marshal if __name__ == '__main__': dict = {'A': 1, 'B': 2, 'C': 3} serialized = marshal.dumps(dict) deserialized = marshal.loads(serialized) print(deserialized) # {'A': 1, 'B': 2, 'C': 3} |
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.
|
1 2 3 4 5 6 7 8 9 |
import json if __name__ == '__main__': dict = {'A': 1, 'B': 2, 'C': 3} serialized = json.dumps(dict) print(serialized) # {"A": 1, "B": 2, "C": 3} |
To deserialize a dictionary, i.e., convert serialized data back to a dictionary, call the loads() function:
|
1 2 3 4 5 6 7 8 9 |
import json if __name__ == '__main__': serialized = '{"A": 1, "B": 2, "C": 3}' dict = json.loads(serialized) print(type(dict)) # <class 'dict'> |
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.
|
1 2 3 4 5 6 7 |
if __name__ == '__main__': dict = {'A': 1, 'B': 2, 'C': 3} serialized = str(dict) print(serialized) # {'A': 1, 'B': 2, 'C': 3} |
Then use the literal_eval() function from the ast module to safely deserialize the string containing a Python dictionary.
|
1 2 3 4 5 6 7 8 9 |
import ast if __name__ == '__main__': serialized = "{'A': 1, 'B': 2, 'C': 3}" dict = ast.literal_eval(serialized) print(type(dict)) # <class 'dict'> |
That’s all about converting a dictionary to a string in Python.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)