- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How do I serialize a Python dictionary into a string, and then back to a dictionary?
The JSON module is a very reliable library to serialize a Python dictionary into a string, and then back to a dictionary. The dumps function converts the dict to a string.
example
import json my_dict = { 'foo': 42, 'bar': { 'baz': "Hello", 'poo': 124.2 } } my_json = json.dumps(my_dict) print(my_json)
Output
This will give the output −
'{"foo": 42, "bar": {"baz": "Hello", "poo": 124.2}}'
The loads function converts the string back to a dict.
example
import json my_str = '{"foo": 42, "bar": {"baz": "Hello", "poo": 124.2}}' my_dict = json.loads(my_str) print(my_dict['bar']['baz'])
Output
This will give the output −
Hello
Advertisements