How to store and retrieve a dictionary with redis

前端 未结 11 1305
遇见更好的自我
遇见更好的自我 2020-12-07 10:20
# I have the dictionary my_dict
my_dict = {
    \'var1\' : 5
    \'var2\' : 9
}
r = redis.StrictRedis()

How would I store my_dict and retrieve it w

11条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-07 10:46

    If you want to store a python dict in redis, it is better to store it as json string.

    import redis
    
    r = redis.StrictRedis(host='localhost', port=6379, db=0)
    mydict = { 'var1' : 5, 'var2' : 9, 'var3': [1, 5, 9] }
    rval = json.dumps(mydict)
    r.set('key1', rval)
    

    While retrieving de-serialize it using json.loads

    data = r.get('key1')
    result = json.loads(data)
    arr = result['var3']
    

    What about types (eg.bytes) that are not serialized by json functions ?

    You can write encoder/decoder functions for types that cannot be serialized by json functions. eg. writing base64/ascii encoder/decoder function for byte array.

提交回复
热议问题