Python | Convert dictionary object to string

Let`s see how you can change the dictionary to string.

Methods # 1: Using json.dumps()

json.dumps () — built-in function in json library. It takes precedence over pickle because it has cross-platform support.

# Python code for demo
# convert dictionary to string
# using json.dumps ()

 

import json

 
# initializing dictionary

test1 = { " testname " : "akshat" ,

"test2name" : "manjeet" < code class = "plain">,

"test3name" : "nikhil" }

  
# print original dictionary

print ( type (test1))

print ( "initial dictionary =" , test1 )

 
# convert dictionary to string
# using json.dumps ()

result = json.dumps (test1)

 
# oven output as a string

print ( "" , type (result))

print ( "final string =" , result)

Output:

& lt; class `dict` & gt;
initial dictionary = {`testname`: `akshat`, `test2name`: `manjeet`, `test3name`: `nikhil`}

& lt; class `str` & gt;
final string = {“testname”: “akshat”, “test2name”: “manjeet”, “test3name”: “nikhil”}

Methods # 2: Using str()

The str () function converts the specified value to a line.

# Python code for demonstration
# convert dictionary to string
# using str ()

 
# initializing dictionary

test1 = { " testname " : "akshat" ,

"test2name" : "manjeet" ,

"test3name" : "nikhil" }

 
# print the original dictionary

print < / code> ( type (test1))

print ( "initial dictionary =" , test1)

  
# convert dictionary to string
# using page

result = str (test1)

  
# print the resulting string

print ( "" , type (result))

print ( "final string =" , result)

Output:

& lt; class` dict `& gt;
initial dictionary = {` test2name `:` manjeet `,` testname `:` akshat `,` test3name `:` nikhil `}

& lt; class` str` & gt;
final string = {`test2name`: `manjeet`, `testname`: `akshat`, `test3name`: `nikhil`}