'Python, redis: How do I set multiple key-value pairs at once
I have two lists keys= [k0,k1, ....kn] vals= [v0,v1, ....vn]
I can set these key-values on redis in multiple steps doing the following:
for i in range(0,len(keys)):
redis_con.set(keys[i], vals[i])
But this is multiple set operations.
How can I do this in one async step?
Solution 1:[1]
Assuming you want a single redis call for set ops:
pipe = redis_con.pipeline()
for i in range(0,len(keys)):
pipe.set(keys[i], vals[i])
pipe.execute()
Solution 2:[2]
keys= ["k0","k1"]
vals= ["v0","v1"]
# use zip or izip based on py
res = set(zip(keys, vals))
print res
>>> set([('k0', 'v0'), ('k1', 'v1')])
Solution 3:[3]
You can, also, do it with a custom method like this way:
a = [["b", "k", "a"], ["c", "m", "a"], ["a", "j","c"]]
b = [["k","a", "l"], ["l", "f", "c"], ["c", "d", "b"]]
def get_sets(*args):
final = []
for v in args:
for j in v:
final.append(set(j))
yield final
final = []
print(list(get_sets(a,b)))
Output:
[
[
{'b', 'k', 'a'}, {'c', 'a', 'm'}, {'c', 'j', 'a'}
],
[
{'l', 'k', 'a'}, {'c', 'f', 'l'}, {'c', 'd', 'b'}
]
]
Solution 4:[4]
For Django people who landed here, and if you are using django-redis, you can use .set_many()
method.
from django.core.cache import cache
my_dict = {'key1': 'val1', 'key2': 'val2', 'key3'}
cache.set_many(my_dict, timeout=60*60)
This will create 3 keys in the cache. Internally it uses redis pipeline.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Sooraj |
Solution 2 | |
Solution 3 | Itamar Haber |
Solution 4 | Gaurav Jain |