Posted on 10th September 2024|24 views
How can we convert a dictionary to string in python?
Posted on 10th September 2024| views
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.