Skip to content

Instantly share code, notes, and snippets.

@vladignatyev
Last active October 28, 2024 09:40
Show Gist options
  • Save vladignatyev/722551de2a992577a2cd to your computer and use it in GitHub Desktop.
Save vladignatyev/722551de2a992577a2cd to your computer and use it in GitHub Desktop.
Save Python dict to Redis hash
def dict_to_redis_hset(r, hkey, dict_to_store):
"""
Saves `dict_to_store` dict into Redis hash, where `hkey` is key of hash.
>>> import redis
>>> r = redis.StrictRedis(host='localhost')
>>> d = {'a':1, 'b':7, 'foo':'bar'}
>>> dict_to_redis_hset(r, 'test', d)
True
>>> r.hgetall('test')
{'a':1, 'b':7, 'foo':'bar'}
"""
return all([r.hset(hkey, k, v) for k, v in dict_to_store.items()])
@AHassanSOS
Copy link

Does anyone know how to store a dict value? I get this error when I try to map a key to a dict value

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

@fefefefta
Copy link

fefefefta commented Oct 28, 2024

If someone notices that even with mapping attribute you get DataError: Invalid input of type: 'dict'. Convert to a bytes, string, int or float first. when trying to set dict as value, check that values inside the dict are also ints, bytes or strs. I was trying to hset with ...mapping={'mapping': {'nested_mapping': 'which i have not noticed'}}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment