【问题标题】:msgpack dictionary with tuple keys带有元组键的 msgpack 字典
【发布时间】:2021-03-27 19:42:02
【问题描述】:
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?

【问题讨论】:

    标签: python python-3.x msgpack


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2020-05-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-25
      • 2012-09-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多