如何使用msgpack序列化/反序列化字典data
?
答案 0 :(得分:18)
Python docs似乎不太好,所以这是我的尝试。
pip install msgpack
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import msgpack
# Define data
data = {'a list': [1, 42, 3.141, 1337, 'help'],
'a string': 'bla',
'another dict': {'foo': 'bar',
'key': 'value',
'the answer': 42}}
# Write msgpack file
with open('data.msgpack', 'w') as outfile:
msgpack.pack(data, outfile)
# Read msgpack file
with open('data.msgpack') as data_file:
# data_loaded = json.load(data_file)
data_loaded = msgpack.unpack(data_file)
print(data == data_loaded)
对于您的应用程序,以下内容可能很重要:
另请参阅:Comparison of data serialization formats
如果您正在寻找制作配置文件的方法,您可能需要阅读我的简短文章Configuration files in Python