How do I serialize a Python dictionary into a string and vice versa?

PythonServer Side ProgrammingProgramming

The best representation for a python dictionaty in string is JSON. you can use the json.dumps(dict) to convert the dictionary to string. And you can use json.loads(string) to get the dictionary back from the string.


For example, we serialize given dictionary as follows.

>>> import json
>>> d = {'id': 15, 'name': 'John'}
>>> x = json.dumps(d)
>>> print x
{"id": 15, "name": "John"}
>>> print json.loads(x)
{u'id': 15, u'name': u'John'}

This is the easiest and fastest way to serialize and deserialize Python dictionaries.

Updated on 17-Dec-2019 06:51:59