python 3将无法从msgpack中找到字典中的键 [英] python 3 will not find key in dict from msgpack

查看:361
本文介绍了python 3将无法从msgpack中找到字典中的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么在python3中会发生这种情况?

why does this happen in python3?

1)我从redis获取msgpack数据

1) I get msgpack data from redis

2)打开包装,我得到下面的东西

2) I unpack I get the below

3)返回的类型是字典:

3) The returned type is a dict:

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']

If I run the below: 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'],那么它将起作用.

but if I use sensor_meta[b'sensor_id'] then it works.

"b"是什么,我如何摆脱它?我如何转换整个对象,所以没有b?

What is the "b" and how can i get rid of that? How do I convert the whole object so there are no b's ?

因此,如果我执行以下操作:

so if I do the below:

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

为什么字节以及如何到达那里?我不想在每次要在哈希中使用键时都添加b.

why bytes and how did it get there? I do not to append a b for every time I want to use keys in a hash.

谢谢

推荐答案

如注释此处所述:

字符串和二进制类型过去,msgpack不能区分字符串 和二进制类型,例如Python1.代表字符串和 二进制类型被命名为raw.

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现在可以区分字符串和二进制类型.但这不是 像Python 2一样.Python2添加了unicode字符串.但是msgpack重命名为raw 到str和添加的bin类型.这是因为保持与数据的兼容性 由旧库创建. 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.

当前,虽然msgpack-python支持新的bin类型,但默认设置 不使用它,而是将raw解码为字节而不是unicode(str in Python 3).

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).

您可以通过使用Packer中的use_bin_type = True选项来更改此设置,然后 Unpacker中的encoding =" utf-8"选项.

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']

您可以在解压缩时定义编码,以将字节转换为字符串.

You can define an encoding while unpacking to convert your bytes to strings.

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

这篇关于python 3将无法从msgpack中找到字典中的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆