redis.exceptions.DataError: Invalid input of type: 'dict'. Convert to a bytes, string, int or float first
Asked Answered
A

1

8

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.
Ambie answered 18/1, 2023 at 9:58 Comment(0)
A
17

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)
Ambie answered 18/1, 2023 at 9:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.