How to Use Redis ZADD and ZRANGE in Python
Add members to a Redis sorted set with ZADD and retrieve them in score order with ZRANGE in Python.
pip install redis
Python code
12 linesimport redis
client = redis.Redis(host='localhost', port=6379, db=0)
client.delete('scores')
members = {'alice': 30, 'bob': 20, 'carol': 50}
for name, score in members.items():
client.zadd('scores', {name: score})
result = client.zrange('scores', 0, -1)
print(result)
Output
['bob', 'alice', 'carol']
How it works
ZADD inserts each member with an associated score into a Redis sorted set. ZRANGE returns members in ascending score order (and lexicographically for ties). The 0, -1 range means from the first to the last element, so the entire set is fetched. The result is a list of member names (bytes by default, though the output shows strings for clarity). This is efficient even for large sets because Redis uses skip lists internally.
Common mistakes
- Forgetting to delete the key before running again, causing duplicate entries.
- Passing a tuple (name, score) instead of a dict to ZADD.
- Assuming ZRANGE returns scores; you need WITHSCORES for that.
Variations
- Use `zrevrange(0, -1)` to get elements in descending score order.
- Use `zrange(0, -1, withscores=True)` to include scores in the result.
Real-world use cases
- Leaderboards: store player scores and fetch top players in rank order.
- Priority queues: process tasks in order of priority stored as scores.
- Time-series data: use timestamp as score to retrieve recent events.
Sponsored
More from Caching & Redis
- Cache Asides in Python with a Read-Through Loader easy
- Cache Data in Redis with Python easy
- Cache Penetration Null Object Mock in Python medium
- Cache Stampede Prevention with SingleFlight in Python medium
- Cache Warming with Python: Preload Hot Keys easy
- Coalescing duplicate in-flight requests: one shared result for concurrent callers hard
Keep learning
Related tutorials and quizzes for this topic.