Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Serialize Python dictionary thành string và ngược lại

Biểu diễn tốt nhất cho Python dictionary trong string là JSON. Dùng json.dumps(dict) convert dict thành string. Dùng json.loads(string) lấy dict ngược từ string.

Ví dụ

Serialize dict cho trước:

>>> 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'}

Đây là cách dễ và nhanh nhất serialize/deserialize Python dictionary.