Redis HASHes are ideal for storing key-value pairs but do not natively support storing Python lists. However, you can store a list in a Redis HASH field by serializing it (e.g. using JSON). Here's how you can do it in Python using the redis
and json
libraries:
import redis
import json
# Connect to Redis
r = redis.Redis(host='localhost', port=6379, db=0)
# Define your list and key
my_list = [1, 2, 3, 4]
hash_key = 'my_hash'
field = 'my_list_field'
# Serialize the list to JSON and store it in the HASH
r.hset(hash_key, field, json.dumps(my_list))
# Retrieve and deserialize the list
stored_list_json = r.hget(hash_key, field)
retrieved_list = json.loads(stored_list_json)
print(retrieved_list) # Output: [1, 2, 3, 4]
pickle
instead, but JSON is safer for inter-language or human-readable needs.Let me know if you want an example using pickle
or handling nested lists/dictionaries!