# 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
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.
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.
Actually, you can store python objects in redis using the built-in module pickle.
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'}
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With