Converting a dictionary into a string is easy in Python. Use the JSON module or str() Method to convert Python dict to string. In this tutorial, you will get the solution with examples.
Way to convert dict to string in Python
- json.dumps() – JSON module
- Using str()
Let’s see the example convert dictionary to a string
Using json.dumps()
You have to import a JSON module and then use the dumps() method to convert dict to string. The dumps() method is an inbuilt function in the JSON library.
import json # dictionary test1 = {"emp1": "Johan", "emp2": "Kavin", "emp3": "Trump"} # original dictionary print(type(test1)) print("initial dictionary = ", test1) # convert dictionary into string result = json.dumps(test1) # result as string print("\n", type(result)) print("final string = ", result)
Output:
Using str()
The str() function has not required any module or library, you can use it directly to Convert the dictionary into a string. See below example of it:-
# dictionary test1 = {"emp1": "Johan", "emp2": "Kavin", "emp3": "Trump"} # original dictionary print(type(test1)) print("initial dictionary = ", test1) # convert dictionary into string result = str(test1) # print resulting string print("\n", type(result)) print("final string = ", result)
Output:
Do comment if you have any doubts and suggestions on this tutorial.
Note: This example (Project) is developed in PyCharm 2018.2 (Community Edition)
JRE: 1.8.0
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.13.6
Python 3.7
All Python Programs are in Python 3, so it may change its different from python 2 or upgraded versions.