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?
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'}