带有元组键的msgpack字典

2024-09-24 02:21:18 发布

您现在位置:Python中文网/ 问答频道 /正文

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

(只有在拆包时才会检测到错误,这不是很奇怪吗?)

如何编写或解决msgpacking一个以元组为键的python dict


Tags: pathintestimportas错误withline
1条回答
网友
1楼 · 发布于 2024-09-24 02:21:18

这里有两个问题:msgpack在默认情况下使用strict_map_key=True,因为版本1.0.0source)和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'}

相关问题 更多 >