David542
David542

Reputation: 110502

Get zrange with score

Is it possible to get a list of tuples of the elements with their score in a ZSET? For example:

redis.zrange-function('channel', 0, -1)
[('item1', 123), ('item2', 333), etc.]

Upvotes: 0

Views: 9097

Answers (1)

alkasm
alkasm

Reputation: 23052

For redis-py, there's an optional argument for that in zrange() as per the docs for zrange():

zrange(name, start, end, desc=False, withscores=False, score_cast_func=<type 'float'>)

Return a range of values from sorted set name between start and end sorted in ascending order.

...

withscores indicates to return the scores along with the values. The return type is a list of (value, score) pairs

Example:

In [292]: import redis

In [293]: r = redis.Redis()

In [294]: r.zadd('channel', 'a', 0, 'b', 5, 'c', 8, 'd', 20)
Out[294]: 4

In [295]: r.zrange('channel', 0, -1, withscores=True)
Out[295]: [(b'a', 0.0), (b'b', 5.0), (b'c', 8.0), (b'd', 20.0)]

Upvotes: 4

Related Questions