问题描述
import msgpack
path = 'test.msgpack'
with open(path,"wb") as outfile:
outfile.write(msgpack.packb({ (1,2): 'str' }))
工作正常,现在
with open(path,'rb') as infile:
print(msgpack.unpackb(infile.read()))
Traceback (most recent call last):
File "<stdin>",line 2,in <module>
File "msgpack/_unpacker.pyx",line 195,in msgpack._cmsgpack.unpackb
ValueError: list is not allowed for map key
(只有在解包时才检测到错误是不是很奇怪?)
如何编写或解决将元组作为键的 python dict msgpacking 的方法?
解决方法
这里有两个问题:msgpack
默认使用 strict_map_key=True
,因为版本 1.0.0 (source) 和 msgpack 的数组被隐式转换为 Python 的lists
- 不可散列。为了使事情工作,传递所需的关键字参数:
with open(path,"rb") as f:
print(msgpack.unpackb(f.read(),use_list=False,strict_map_key=False))
# outputs: {(1,2): 'str'}