简体   繁体   中英

redis py and hgetall - why key values have a b“”?

Below is the dict return from redis. Why the b? How do I get rid of it?

data = r_client.hgetall(key)
{b'test1:r': b'2', b'test2:f': b'2'}

print('test1:r' in data)
False

print(b'test1:r' in data)
True

When I get data from redis how do I get rid of that terrible b?

I mean I have do this to get what I want:

new_data = {}
for key,value in data.items():
    new_data[key.decode()] = value.decode()

you need to decode the bytes of a string:

b'test1:r'.decode('utf-8')

decode all your keys:

data = {b'test1:r': b'2', b'test2:f': b'2'}
data= {key.decode('utf-8'):value for key,value in data.items()}
print('test1:r' in data) # True
print(b'test1:r' in data) # False

您可以添加参数来摆脱这种情况。

client = redis.Redis('localhost', charset="utf-8", decode_responses=True)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM