xin.chen
xin.chen

Reputation: 986

pythonic way deal with DataError: Invalid input of type: 'dict'. Convert to a bytes, string, int or float first.?

redis veersion 3.4.1 must be use hash, can't use str or other data type data:

{
    '_anno': {
        'ctp': 'list',
        'dt': [],
        'ml': 0,
        'na': 'apple',
        'pos': -1,
        'rel': '',
        'st_var': '',
        'tp': 'object'
    },
    '_att': {
        '_cuser': 'apple card',
        '_last_editor': 'apple card',
        '_protext': 'authorize',
        '_status': 'normal',
        '_theme_id': 'apple card',
        '_view': '12'
    }
}

my code

pool = redis.ConnectionPool(host=host, port=port)
conn = redis.StrictRedis(connection_pool=pool)

conn.hmset("aaaaaa",data)

raise error

DataError: Invalid input of type: 'dict'. Convert to a bytes, string, int or float first.

now code

pool = redis.ConnectionPool(host=host, port=port)
conn = redis.StrictRedis(connection_pool=pool)
new_data={}
for key,value in data.items():
    new_data[key]=json.dumps(value)
conn.hmset("aaaaaa",new_data)

Is there a more pythonic way?

Upvotes: 7

Views: 12209

Answers (2)

Don
Don

Reputation: 17606

Maybe a more pythonic way would be something like:

pool = redis.ConnectionPool(host=host, port=port)
conn = redis.StrictRedis(connection_pool=pool)
new_data=dict(k, json.dumps(v) for (k, v) in data.items())
conn.hmset("aaaaaa", new_data)

but it very depends on how the original dictionary is built:

if all its values are dictionaries, then that's ok; but it they are mixed values, you should consider dumping selected values explicitely:

...
new_data = {
    '_anno': json.dumps(data['_anno']),
    '_att': json.dumps(data['_att']),
    'int_value': data['int_value'],
    'str_value': data['str_value'],
    ...
}

Maybe you can also find some generic solution:

SAFE_TYPES = (int, str, bool, bytes, float)
new_data = {
    k: v if isinstance(v, SAFE_TYPES) else json.dumps(v)
    for k, v in data.items()
}

Upvotes: 0

StarGit
StarGit

Reputation: 35

The solution for you problem is to use hexdigest() or digest() to convert your dictionary, you can use that:

hashlib.sha256(mdp.encode()).hexdigest()

Upvotes: 1

Related Questions