How do I serialize a Python dictionary into a string, and then back to a dictionary?

PythonProgramming

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
raja
Published on 18-Apr-2018 16:20:50
Advertisements