Here are 3 ways to convert a dictionary to a string in Python:
- Using json.dumps()
- Using str()
- Using repr()
Method 1: Using json.dumps()
The json.dumps() method from json module easily converts dictionary into string. This method is particularly useful if you need to send the dictionary over a network or store it in a way that it can be easily read back into a dictionary.
Visual Representation
Example
import json
# declaring a dictionary
dict = {'Name': 'Millie', 'Age': 18, 'City': 'Atlanta'}
# print original dictionary
print("Dictionary = ", dict)
print(type(dict))
str = json.dumps(dict)
# printing result as string
print("String = ", str)
print(type(str))
Output
Dictionary = {'Name': 'Millie', 'Age': 18, 'City': 'Atlanta'}
<class 'dict'>
String = {"Name": "Millie", "Age": 18, "City": "Atlanta"}
<class 'str'>
Method 2: Using str()
The str() function can take a dictionary object as an input and returns its string representation.
Visual Representation
Example
# declaring a dictionary
dict = {'Name': 'Millie', 'Age': 18, 'City': 'Atlanta'}
# print original dictionary
print("Dictionary = ", dict)
print(type(dict))
# convert dictionary into string using str()
str = str(dict)
# printing result as string
print("String = ", str)
print(type(str))
Output
Dictionary = {'Name': 'Millie', 'Age': 18, 'City': 'Atlanta'}
<class 'dict'>
String = {'Name': 'Millie', 'Age': 18, 'City': 'Atlanta'}
<class 'str'>
Method 3: Using repr()
The repr() function is a built-in function used to get a string representation of an object. It is mainly used for debugging and development purposes.
import json
# declaring a dictionary
dict = {'Name': 'Millie', 'Age': 18, 'City': 'Atlanta'}
# print original dictionary
print("Dictionary = ", dict)
print(type(dict))
str = repr(dict)
# printing result as string
print("String = ", str)
print(type(str))
Output
Dictionary = {'Name': 'Millie', 'Age': 18, 'City': 'Atlanta'}
<class 'dict'>
String = {'Name': 'Millie', 'Age': 18, 'City': 'Atlanta'}
<class 'str'>
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.