How to Convert Dictionary to String in Python

Here are 3 ways to convert a dictionary to a string in Python:

  1. Using json.dumps()
  2. Using str()
  3. 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

Visual Representation of Convert Dictionary to String in Python

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

Visual Representation of Using str()

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'>

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.