简体   繁体   中英

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?

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')])

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'}
  ]
]

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()

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM