user
How to store a list in a Redis HASH item in Python?
alphonsio

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:

Example: Storing a list in a Redis HASH field

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]

Notes:

  • JSON serialization is simple and portable.
  • If you're storing complex objects, you can use pickle instead, but JSON is safer for inter-language or human-readable needs.
  • Redis itself is string-based, so anything not a simple string or number must be encoded.

Let me know if you want an example using pickle or handling nested lists/dictionaries!