Convert dictionary object into string in Python

PythonServer Side ProgrammingProgramming

For data manipulation in python we may come across situation to convert a dictionary object into a string object. This can be achieved in the following ways.

with str()

In this straight forward method we simple apply the str() by passing the dictionary object as a parameter. We can check the type of the objects using the type() before and after conversion.

Example

 Live Demo

DictA = {"Mon": "2 pm","Wed": "9 am","Fri": "11 am"}
print("Given dictionary : 
", DictA) print("Type : ", type(DictA)) # using str res = str(DictA) # Print result print("Result as string:
", res) print("Type of Result: ", type(res))

Output

Running the above code gives us the following result −

Given dictionary :
{'Mon': '2 pm', 'Wed': '9 am', 'Fri': '11 am'}
Type :
Result as string:
{'Mon': '2 pm', 'Wed': '9 am', 'Fri': '11 am'}
Type of Result:

With json.dumps

The json module gives us dumps method. Through this method the dictionary object is directly converted into string.

Example

 Live Demo

import json
DictA = {"Mon": "2 pm","Wed": "9 am","Fri": "11 am"}
print("Given dictionary : 
", DictA) print("Type : ", type(DictA)) # using str res = json.dumps(DictA) # Print result print("Result as string:
", res) print("Type of Result: ", type(res))

Output

Running the above code gives us the following result −

Given dictionary :
{'Mon': '2 pm', 'Wed': '9 am', 'Fri': '11 am'}
Type :
Result as string:
{"Mon": "2 pm", "Wed": "9 am", "Fri": "11 am"}
Type of Result:
raja
Updated on 20-May-2020 10:51:52

Advertisements