3

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?

Dumbo
  • 1,068
  • 2
  • 12
  • 21
  • I think you want this: `{key: value for key, value in zip(keys, vals)}`. – Elmex80s Feb 16 '17 at 15:57
  • The question is not about getting a new dataframe. It is about setting a number of keys and values in one step, instead of doing a for loop to set one key-value pair at one time. – Dumbo Feb 16 '17 at 16:57
  • If you are asking on doing it in a single redis call, use redis pipeline – Sooraj Feb 16 '17 at 18:03

4 Answers4

6

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()
Sooraj
  • 412
  • 4
  • 11
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')])
Ari Gold
  • 1,528
  • 11
  • 18
2

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'}
  ]
]
Itamar Haber
  • 47,336
  • 7
  • 91
  • 117
Chiheb Nexus
  • 9,104
  • 4
  • 30
  • 43
0

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.

Gaurav Jain
  • 1,549
  • 1
  • 22
  • 30