1

I am using Python as client to interact with redis and using the following Python library to do so: https://github.com/redis/redis-py

When I run the command:

redis_return = conn.hgetall('my-hash-key')

What I get in return is a dictionary with all its elements as bytes objects individually, like:

{b'key1': b'value1', b'key2': b'value2'}

Since I need them as string I am looping over the dictionary and on each iteration decoding they key and value, something like:

mydict = dict()
for keys in redis_return:
    mydict[keys.decode('utf-8')] = redis_return[keys].decode('utf-8')

I am getting the results in mydict as I need it, but is this the right approach? Seems tedious and I wonder if there is a better way?

Ankit Sahay
  • 1,710
  • 8
  • 14
  • 2
    As noted [here](https://stackoverflow.com/questions/44026515/python-redis-keys-returns-list-of-bytes-objects-instead-of-strings) you need to pass `decode_responses=True` when you create your connection. – Kevin Christopher Henry Jul 28 '22 at 19:18
  • This seems to be a life saver. My code is full of response.decode('utf-8') splattered all over the place! – Ankit Sahay Jul 29 '22 at 09:50

0 Answers0