Goal: store a dict()
or {}
as the value for a key-value pair, to set()
onto Redis.
Code
import redis
r = redis.Redis()
value = 180
my_dict = dict(bar=value)
r.set('foo', my_dict)
redis.exceptions.DataError: Invalid input of type: 'dict'. Convert to a bytes, string, int or float first.
You cannot pass a dictionary object as a value in the set()
operation to Redis.
However, we can use either pickle
or json
to get the Bytes
of an object.
Whichever you already have imported would be optimal, imho.
Pickle
Serialize to pickle (with pickle.dumps
) pre-set()
import pickle
my_dict = {'a': 1, 'b': 2}
dict_bytes = pickle.dumps(my_dict)
r.set('my_key', dict_bytes)
Deserialize the object (dict) (with pickle.loads
) post-get()
:
dict_bytes = r.get('my_key')
my_dict = pickle.loads(dict_bytes)
JSON string
Serialize to JSON string (with json.dumps
) pre-set()
import json
my_dict = {'a': 1, 'b': 2}
dict_str = json.dumps(my_dict)
r.set('my_key', dict_str)
Deserialize the object (dict) (with json.loads
) post-get()
:
dict_str = r.get('my_key')
my_dict = json.loads(dict_str)