How to store and retrieve a dictionary with redis

前端 未结 11 1302
遇见更好的自我
遇见更好的自我 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

    The redis SET command stores a string, not arbitrary data. You could try using the redis HSET command to store the dict as a redis hash with something like

    for k,v in my_dict.iteritems():
        r.hset('my_dict', k, v)
    

    but the redis datatypes and python datatypes don't quite line up. Python dicts can be arbitrarily nested, but a redis hash is going to require that your value is a string. Another approach you can take is to convert your python data to string and store that in redis, something like

    r.set('this_dict', str(my_dict))
    

    and then when you get the string out you will need to parse it to recreate the python object.

提交回复
热议问题