Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store and retrieve a dictionary with redis

Tags:

python

redis

# I have the dictionary my_dict my_dict = {     'var1' : 5     'var2' : 9 } r = redis.StrictRedis() 

How would I store my_dict and retrieve it with redis. For example, the following code does not work.

#Code that doesn't work r.set('this_dict', my_dict)  # to store my_dict in this_dict r.get('this_dict')  # to retrieve my_dict 
like image 525
PiccolMan Avatar asked Aug 28 '15 17:08

PiccolMan


People also ask

How do I save a dictionary in Redis?

you can pickle your dict and save as string. pickle can be dangerous if mishandled. Use msgpack for better serialization of data before storing it into Redis. Pickling has also the important down-part that you cannot debug the stored data in Redis as they are binary.

How do you store a dictionary?

Saving Dictionary to a File This method would include the following steps: Opening a file in write/append text mode. Converting the dictionary into a string. Entering the converted string into the file using write function.

Can Redis store Python objects?

Actually, you can store python objects in redis using the built-in module pickle.


2 Answers

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'} 
like image 173
PradeepK Avatar answered Oct 17 '22 07:10

PradeepK


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) 
like image 32
DaveQ Avatar answered Oct 17 '22 06:10

DaveQ