Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

msgpack dictionary with tuple keys

import msgpack
path = 'test.msgpack'
with open(path, "wb") as outfile:
    outfile.write(msgpack.packb({ (1,2): 'str' }))

works fine, now

with open(path, 'rb') as infile:
    print(msgpack.unpackb(infile.read()))

errors with

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

(Isn't it totally bizarre the error is only detected during unpacking?)

How can I write or workaround msgpacking a python dict with tuples as keys?


1 Answers

There are two issues here: msgpack is using strict_map_key=True by default since version 1.0.0 (source) and msgpack's arrays are implicitly converted to Python's lists - which are not hashable. To make things work, pass the needed keyword arguments:

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

# outputs: {(1, 2): 'str'}
like image 59
Paweł Rubin Avatar answered Apr 29 '26 03:04

Paweł Rubin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!