0

I have a Python list of tuples like so:

lst = [(22, -150.0), (23, -150.0), (18, -148.5), (15, -99.4), (5, -75.75), (4, -49.2), (13, -49.0), (9, -41.3), (20, -25.5), (17, -22.3), (10, -13.1), (16, -12.5), (14, -9.8), (3, -8.5), (1, -8.4), (12, -1.5), (7, -0.6), (2, -0.4), (6, 1.7), (21, 2.7)]

How do I pass that into a redis sorted set, such that the second value in each tuple is used as the score? I tried zadd(sorted_set, *lst), but I'm getting the error value is not a valid float.

vaultah
  • 44,105
  • 12
  • 114
  • 143
Hassan Baig
  • 15,055
  • 27
  • 102
  • 205

1 Answers1

3

The zadd method of redis.StrictRedis expects arguments in the form of

zadd(key, score1, name1, score2, name2, ...)

In other words, you need to reverse and unpack the inner tuples as well:

In [6]: r = redis.StrictRedis(...)

In [8]: r.zadd('sset', *(y for x in lst for y in x[::-1]))
Out[8]: 20

Redis.zadd and StrictRedis.zadd behave differently -- see README for more details. So if you use redis.Redis instead of redis.StrictRedis (you shouldn't), do not reverse tuples:

r.zadd('sset', *(y for x in lst for y in x))
vaultah
  • 44,105
  • 12
  • 114
  • 143