繁体   English   中英

带有元组键的 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

(仅在拆包过程中才检测到错误,这不是很奇怪吗?)

如何编写或解决 msgpacking 以元组为键的 python 字典?

这里有两个问题:自版本1.0.0 ( source ) 以来, msgpack默认使用strict_map_key=True ,并且 msgpack 的 arrays 被隐式转换为 Python 的lists - 这是不可散列的。 要使事情正常进行,请传递所需的关键字 arguments:

with open(path, "rb") as f:
    print(msgpack.unpackb(f.read(), use_list=False, strict_map_key=False))

# outputs: {(1, 2): 'str'}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM