Skip to content

Instantly share code, notes, and snippets.

@vladignatyev
Last active November 23, 2022 01:00
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • 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()])
@endophage
Copy link

Or you could simply use hmset: https://redis-py.readthedocs.org/en/latest/#redis.StrictRedis.hmset

r.hmset(hkey, dict_to_store)

Redis supports setting multiple key:value pairs on a hash as a single operation so this is not only faster but more atomic.

@itamarhaber
Copy link

@endophage - great catch, thanks for the code review :)

@hypergig
Copy link

Just learning redis now but wouldn't you want a pipeline here?

@iamrochit
Copy link

hey!
please upload the definition of the function dict_to_redis_hset

@vcmorini
Copy link

hmset is deprecated

@mirekphd
Copy link

mirekphd commented Nov 21, 2022

Given that hmset is deprecated, for dictionaries we can use hset, like this (do not skip the named mapping arg):

r.hset(hkey, mapping=dict_to_store)

See in redis-py docs.

@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.

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