Dragonfly

Redis Get All Keys in Python (Detailed Guide w/ Code Examples)

In this guide, we will learn about how to read all keys in Redis with hands-on code examples in Python.

July 18, 2025

Redis vs. Memcached: 7 Key Differences and How to Choose

Use Case(s)

  • Enumerating all keys in a Redis server in Python is useful for debugging, administration, and maintenance tasks.
  • It's also used when you want to perform operations on all keys or a subset of keys in the data store.

Code Examples

Here's how to get all keys from a Redis server using the redis-py package for Python:

import redis

r = redis.Redis(host='localhost', port=6379, db=0)

for key in r.scan_iter():
    print(key)

In this code snippet, we're connecting to the Redis server, then using the scan_iter() function (which uses Redis' SCAN command underneath) to iteratively access each key in the database. Each key is printed to the console.

Best Practices

The KEYS command can also retrieve all keys, but it may lead to performance issues in a production environment due to the fact that it may need to read a large number of keys all at once. It's recommended to use the scan_iter() method for such cases, as it reads smaller batches of keys and does not block the server for a long time.

FAQs

1. Why should I avoid KEYS?

KEYS can cause performance issues, especially with larger datasets. Use scan_iter() instead, which scans a small batch of keys per iteration.

2. Can I filter keys when retrieving them?

Yes, you can use pattern matching inside scan_iter(). For example, scan_iter('user:*') will return all keys that start with user:.


Was this content helpful?

Help us improve by giving us your feedback.

Dragonfly Wings

Stay up to date on all things Dragonfly

Join our community for unparalleled support and insights

Join

Switch & save up to 80%

Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement. Instantly experience up to a 25X boost in performance and 80% reduction in cost