Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use sadd with multiple elements in Redis using Python API?

Please consider the following example

>>import redis
>>redis_db_url = '127.0.0.1'
>>r = redis.StrictRedis(host = redis_db_url,port = 6379,db = 0)
>>r.sadd('a',1)
>>r.sadd('a',2)
>>r.sadd('a',3)
>>r.smembers('a')

[+] output: set(['1', '3', '2'])

>>r.sadd('a',set([3,4]))
>>r.smembers('a')

[+] output: set(['1', '3', '2', 'set([3, 4])'])

 >>r.sadd('a',[3,4])
 >>r.smember('a')

[+] set(['1', '[3, 4]', '3', '2', 'set([3, 4])'])

According to the official documentation in https://redis-py.readthedocs.org/en/latest/ sadd(name, *values) Add value(s) to set name

So is it a bug or I am missing something ?

like image 893
Sourav Sarkar Avatar asked Jun 24 '15 19:06

Sourav Sarkar


2 Answers

When you see the syntax *values in an argument list, it means the function takes a variable number of arguments.

Therefore, call it as

r.sadd('a', 1, 2, 3)

You can pass an iterable by using the splat operator to unpack it:

r.sadd('a', *set([3, 4]))

or

r.sadd('a', *[3, 4])
like image 53
nneonneo Avatar answered Sep 27 '22 17:09

nneonneo


Consider the following:

r.sadd('a', 1, 2, 3)

That should do the trick.

like image 34
Itamar Haber Avatar answered Sep 27 '22 16:09

Itamar Haber