How to store and retrieve a dictionary with redis How to store and retrieve a dictionary with redis python python

How to store and retrieve a dictionary with redis


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

hmset("RedisKey", dictionaryToSet)

import redisconn = 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'}


you can pickle your dict and save as string.

import pickleimport redisr = 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)


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