
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Convert Dictionary Object into String in Python
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
DictA = {"Mon": "2 pm","Wed": "9 am","Fri": "11 am"} print("Given dictionary : \n", DictA) print("Type : ", type(DictA)) # using str res = str(DictA) # Print result print("Result as string:\n", 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
import json DictA = {"Mon": "2 pm","Wed": "9 am","Fri": "11 am"} print("Given dictionary : \n", DictA) print("Type : ", type(DictA)) # using str res = json.dumps(DictA) # Print result print("Result as string:\n", 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:
Advertisements