gpt4 book ai didi

python - 带有元组键的 msgpack 字典

转载 作者:行者123 更新时间:2023-12-04 07:53:16 27 4
gpt4 key购买 nike

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

最佳答案

这里有两个问题: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'}

关于python - 带有元组键的 msgpack 字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66835419/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com