How to use sadd with multiple elements in Redis using Python API?
Solution 1
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])
Solution 2
Consider the following:
r.sadd('a', 1, 2, 3)
That should do the trick.
Related videos on Youtube
Sourav Sarkar
Currently I am studying Computer Science in IIT Kharagpur and working in Web and ML applications. I have some experience in Rest APIs, Android and Windows Phone Development, Amazon Web Services and in Data Analytics
Updated on July 09, 2022Comments
-
Sourav Sarkar almost 2 years
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 ?
-
Seaux about 7 yearsI could be wrong, but i don't think you have to cast as a
set
before unpacking -
nneonneo about 7 yearsNo, you don't, but I was following the example in the author's question. In this case the inline syntax is just a shortcut for indicating that you can do this with an arbitrary set (or indeed, an arbitrary iterable).
-
nneonneo about 7 yearsAnd really, on any recent Python you can just do
*{3, 4}
which is the native syntax for set literals, eliminating the "cast" altogether. -
Seaux about 7 yearsAgreed. I just wanted to clarify the point because I didn't want readers to think you had to cast to
set
for use insadd
or something. I'd recommend editing the answer to separate out the declaration of the iterable (set) in another line or just remove the casting all together.