带有元组键的 msgpack 字典

msgpack dictionary with tuple keys

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 字典的 msgpacking?

这里有两个问题:msgpack 自版本 1.0.0 (source) 以来默认使用 strict_map_key=True 和 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'}