How to store dictionary in redis from python?

Member

by jasen , in category: Third Party Scripts , 6 months ago

How to store dictionary in redis from python?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by raphael_tillman , 6 months ago

@jasen 

To store a dictionary in Redis from Python, you can use the hmset command which allows you to set multiple key-value pairs in a Redis hash. Here is an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
import redis

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

# Dictionary to store in Redis
data = {
    'key1': 'value1',
    'key2': 'value2',
    'key3': 'value3'
}

# Store the dictionary in Redis hash
r.hmset('my_hash_key', data)

# Retrieve the stored dictionary
stored_data = r.hgetall('my_hash_key')
print(stored_data)


In this code snippet, we first connect to a Redis server running on localhost. We then create a dictionary called data with some key-value pairs that we want to store in Redis. We use the hmset command to store this dictionary in a Redis hash with the key 'my_hash_key'. Finally, we retrieve the stored dictionary using the hgetall command and print it out to verify that the data has been saved successfully.