1

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()
Tampa
  • 75,446
  • 119
  • 278
  • 425
  • 1
    Possible duplicate of [What does the 'b' character do in front of a string literal?](https://stackoverflow.com/questions/6269765/what-does-the-b-character-do-in-front-of-a-string-literal) – khelwood Jul 12 '19 at 10:07
  • No does not solve. – Tampa Jul 12 '19 at 10:17
  • 1
    It does solve one of your questions, but you are asking two: 1) What is the `b` character and 2) How do I avoid getting this `b` character from redis. – user2653663 Jul 12 '19 at 10:26
  • If you read [this answer](https://stackoverflow.com/a/6273618/3890632) in the duplicate, it explains how to transform b-strings to strings. – khelwood Jul 12 '19 at 10:34

2 Answers2

10

You can add params to get rid of that.

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

DennisLi
  • 3,915
  • 6
  • 30
  • 66
2

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
ncica
  • 7,015
  • 1
  • 15
  • 37