Convert Dictionary To String In Python

Python provides the dictionary data type in order to store items like keys and value. Dictionary items can be accessed using the keys and the value is returned for different purposes. The string is another type of data where text and other data are stored. As two popular variables or data type converting a dictionary into a string is a popular operation. You may want to save the dictionary data into a file or database where the string is a very convenient and easy format for storage. Even the pickle can be used for storage it is a binary format and can not be read by other programming languages and modules easily. Also, pickle is deprecated for some time and it has cross-platform problems.

Convert Dictionary To String with json.dumps() Method

JSON is a data format which is used to exchange data between different parties. The JSON format is very similar to the Python dictionary data type and the json.dumps() method can be used to convert a dictionary into the string. In order to use the json.dumps() method the json module should be imported.

import json

dct = { "name":"ahmet" , "surname":"ali" , "profession":"footballer"}

print(dct)
print(type(dct))

str = json.dumps(dct)

print(str)
print(type(str))

Convert Dictionary To String with str() Mehtod

Python provides the str() method in order to convert a lot of different data types into the string. Like integer, float the dictionary data type and variables can be converted into a string using str() method. str() method is a built-in method that is provided by default and there is no need to import any module.

dct = { "name":"ahmet" , "surname":"ali" , "profession":"footballer"}

print(dct)
print(type(dct))

str = str(dct)

print(str)
print(type(str))

Convert String To Dictionary with json.loads() Method

If you have converted the dictionary into a srint for later use you will also need to convert back to the dictionary. You can use the json.loads() mehtod which is the convert a string into the dictionary data type. In this case be cautious because the content of the string should be compatible with the dictionary data type.

import json

mystr = '{ "name":"ahmet" , "surname":"ali" , "profession":"footballer"}'

print(mystr )
print(type(mystr ))

mydictionary= json.loads(mystr)

print(mydictionary)
print(type(mydictionary))

Convert String To Dictionary with ast.literal_eval() Method

Python also provides the ast.literal_val() method in order to evaluate strings. This is very useful method where given and evaluated string will be converted into related data type where if the string content is dictionary like with the curly brackets, key-value pairs it will be converted into a dictionary.

import ast

mystr = '{ "name":"ahmet" , "surname":"ali" , "profession":"footballer"}'

print(mystr )
print(type(mystr ))

mydictionary= json.loads(mystr)

print(mydictionary)
print(type(mydictionary))

Leave a Comment