How to store and retrieve a dictionary with redis

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

    you can pickle your dict and save as string.

    import pickle
    import redis
    
    r = redis.StrictRedis('localhost')
    mydict = {1:2,2:3,3:4}
    p_mydict = pickle.dumps(mydict)
    r.set('mydict',p_mydict)
    
    read_dict = r.get('mydict')
    yourdict = pickle.loads(read_dict)
    
    0 讨论(0)
  • 2020-12-07 10:45

    You can do it by hmset (multiple keys can be set using hmset).

    hmset("RedisKey", dictionaryToSet)

    import redis
    conn = redis.Redis('localhost')
    
    user = {"Name":"Pradeep", "Company":"SCTL", "Address":"Mumbai", "Location":"RCP"}
    
    conn.hmset("pythonDict", user)
    
    conn.hgetall("pythonDict")
    
    {'Company': 'SCTL', 'Address': 'Mumbai', 'Location': 'RCP', 'Name': 'Pradeep'}
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-07 10:47

    HMSET is deprecated. You can now use HSET with a dictionary as follows:

    import redis
    r = redis.Redis('localhost')
    
    key = "hashexample" 
    queue_entry = { 
        "version":"1.2.3", 
        "tag":"main", 
        "status":"CREATED",  
        "timeout":"30"
        }
    r.hset(key,None,None,queue_entry)
    
    0 讨论(0)
  • 2020-12-07 10:48

    Another way: you can use RedisWorks library.

    pip install redisworks

    >>> from redisworks import Root
    >>> root = Root()
    >>> root.something = {1:"a", "b": {2: 2}}  # saves it as Hash type in Redis
    ...
    >>> print(root.something)  # loads it from Redis
    {'b': {2: 2}, 1: 'a'}
    >>> root.something['b'][2]
    2
    

    It converts python types to Redis types and vice-versa.

    >>> root.sides = [10, [1, 2]]  # saves it as list in Redis.
    >>> print(root.sides)  # loads it from Redis
    [10, [1, 2]]
    >>> type(root.sides[1])
    <class 'list'>
    

    Disclaimer: I wrote the library. Here is the code: https://github.com/seperman/redisworks

    0 讨论(0)
提交回复
热议问题