gpt4 book ai didi

python-3.x - python 3不会从msgpack中找到dict中的键

转载 作者:行者123 更新时间:2023-12-02 17:28:06 24 4
gpt4 key购买 nike

为什么在python3中会出现这种情况?

1)我从redis获取msgpack数据

2)我打开包装,得到以下内容

3)返回的类型是一个字典:

meta = msgpack.unpackb(data[1])
print(type(meta))
<class 'dict'>

meta = {b'api_key': b'apikey1',
b'sensor_id': b'sid1',
b'version': b'1.0'}

如果我运行以下命令: Sensor_meta['sensor_id']

{b'api_key': b'apikey1',
b'sensor_id': b'sid1',
b'version': b'1.0'}
Traceback (most recent call last):
File "/Users//worker.py", line 247, in <module>
print(meta['sensor_id'])
KeyError: 'sensor_id'

但是如果我使用sensor_meta[b'sensor_id'],那么它就可以工作。

什么是“b”,我怎样才能摆脱它?如何转换整个对象以便不存在 b ?

所以如果我执行以下操作:

   print(type(meta['sensor_id']))
<class 'bytes'>

为什么是字节以及它是如何到达那里的?我不会每次想在哈希中使用键时都附加 b。

谢谢

最佳答案

如注释中所述here :

string and binary type In old days, msgpack doesn’t distinguish string and binary types like Python 1. The type for represent string and binary types is named raw.

msgpack can distinguish string and binary type for now. But it is not like Python 2. Python 2 added unicode string. But msgpack renamed raw to str and added bin type. It is because keep compatibility with data created by old libs. raw was used for text more than binary.

Currently, while msgpack-python supports new bin type, default setting doesn’t use it and decodes raw as bytes instead of unicode (str in Python 3).

You can change this by using use_bin_type=True option in Packer and encoding=”utf-8” option in Unpacker.

>>> import msgpack
>>> packed = msgpack.packb([b'spam', u'egg'], use_bin_type=True)
>>> msgpack.unpackb(packed, encoding='utf-8') ['spam', u'egg']

您可以在解包时定义编码以将字节转换为字符串。

msgpack.unpackb(data[1], encoding='utf-8')

关于python-3.x - python 3不会从msgpack中找到dict中的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46960419/

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