How to convert a dictionary to string in Python:
In this post, we will learn how to convert a dictionary to a string in Python. Dictionaries are used to store key-value pairs in Python. You can’t have two similar keys in a dictionary and we can have different data types as values in a dictionary.
Sometimes you might need to convert a dictionary to a string. For example, if you are doing any string related operations, or if you want to convert it to a string before storing it in your database or before you write the content to a file, you might need this conversion.
There are different ways those can be used to convert a dictionary to string in Python.
Method 1: By using the str() function:
str function can convert other data types to string. If we pass a dictionary, it will convert that dictionary to a string.
For example:
givenDict = {"name": "Alex", "age": 19, "grade": "A"}
convertedStr = str(givenDict)
print(convertedStr)
print(f'type: {type(convertedStr)}')
This example is converting the dictionary givenDict to a string convertedStr.
The last two lines are printing the converted string and its type.
If you run this program, it will print the below output:
{'name': 'Alex', 'age': 19, 'grade': 'A'}
type: <class 'str'>
Method 2: By using the json.dumps() function:
json.dumps is another function that is defined in the json module. json is an inbuilt module of Python and it provides different utility methods related to JSON. We can use dumps method to convert a dictionary to a string in python.
We can pass the dictionary as an argument to this method and it will return the string.
For example:
import json
givenDict = {"name": "Alex", "age": 19, "grade": "A"}
convertedStr = json.dumps(givenDict)
print(convertedStr)
print(f'type: {type(convertedStr)}')
We have to import the json module to use the methods defined in it. If you run this program, it will print output as like below:
{"name": "Alex", "age": 19, "grade": "A"}
type: <class 'str'>