Post

PythonPython

S
Surya kumar

Posted on 19th April 2024|18 views

0
votes

Python Dict To String

How can we convert a dictionary to string in python?

Answers
P
Altaf syed

Posted on 19th April 2024

Let's discuss the various ways of switching the dictionary into a string. json. dumps() remains an inbuilt function within json library.It has an asset over a difficulty because it owns cross-platform support. The str() function changes the particularised value into a string.

Method 1: use of json.dumps()

 import json

# first initialising dictionary

testing = { "name1" : "akash",

          "name2" : "manjari",

          "name3" : "nikhila"}

 # printing the original dictionary

print (type(testing))

print ("The dictionary = ", testing)

# convert dictionary into string

output = json.dumps(testing)

# print the output as string

print ("\n", type(output))

print ("The string = ", output)

Output:

<class’dict’>

The dictionary= {‘name1’: ‘akash’, ‘name2’: ‘manjari’, ‘name3’: ‘nikhila’}

<class ‘str’>

The string= {“name1”: “akash”, “name2”: “manjari”, “name3”: “nikhila”}

 

Method 2: use of str()

# first initialising dictionary

testing = { "name1" : "akash",

          "name2" : "manjari",

          "name3" : "nikhila"}

 # printing the original dictionary

print (type(testing))

print ("The dictionary = ", testing)

# convert dictionary into string

output =str(testing)

# print the output as string

print ("\n", type(output))

print ("The string = ", output)

Output:

<class’dict’>

The dictionary= {‘name1’: ‘akash’, ‘name2’: ‘manjari’, ‘name3’: ‘nikhila’}

<class ‘str’>

The string= {“name1”: “akash”, “name2”: “manjari”, “name3”: “nikhila”}

 


If you are looking for the Python certification course, you can check out this Python course by Mindmajix.

Write your answer

STILL GOT QUERIES?

Get a Live FREE Demo
  • Explore the trending and niche courses and learning maps
  • Learn about tuition fee, payment plans, and scholarships
  • Get access to webinars and self-paced learning videos