作者:沧桑的悟空2502859857 | 来源:互联网 | 2023-06-07 12:10
# I have the dictionary my_dict
my_dict = {
'var1' : 5
'var2' : 9
}
r = redis.StrictRedis()
How would I store my_dict and retrieve it with redis. For example, the following code does not work.
我如何存储my_dict并使用redis检索它。例如,以下代码不起作用。
#Code that doesn't work
r.set('this_dict', my_dict) # to store my_dict in this_dict
r.get('this_dict') # to retrieve my_dict
6 个解决方案
1
As the basic answer has already give by other people, I would like to add some to it.
由于其他人已经给出了基本答案,我想补充一些。
Following are the commands in REDIS
to perform basic operations with HashMap/Dictionary/Mapping
type values.
以下是REDIS中使用HashMap / Dictionary / Mapping类型值执行基本操作的命令。
- HGET => Returns value for single key passed
- HGET =>返回传递的单个键的值
- HSET => set/updates value for the single key
- HSET =>设置/更新单个键的值
- HMGET => Returns value for single/multiple keys passed
- HMGET =>返回传递的单个/多个键的值
- HMSET => set/updates values for the multiple key
- HMSET =>设置/更新多个键的值
- HGETALL => Returns all the (key, value) pairs in the mapping.
- HGETALL =>返回映射中的所有(键,值)对。
Following are their respective methods in redis-py
library :-
以下是redis-py库中各自的方法: -
- HGET => hget
- HGET => hget
- HSET => hset
- HSET => hset
- HMGET => hmget
- HMGET => hmget
- HMSET => hmset
- HMSET => hmset
- HGETALL => hgetall
- HGETALL => hgetall
All of the above setter methods creates the mapping, if it doesn't exists. All of the above getter methods doesn't raise error/exceptions, if mapping/key in mapping doesn't exists.
如果映射不存在,则所有上述setter方法都会创建映射。如果映射中的映射/键不存在,则所有上述getter方法都不会引发错误/异常。
Example:
=======
In [98]: import redis
In [99]: cOnn= redis.Redis('localhost')
In [100]: user = {"Name":"Pradeep", "Company":"SCTL", "Address":"Mumbai", "Location":"RCP"}
In [101]: con.hmset("pythonDict", {"Location": "Ahmedabad"})
Out[101]: True
In [102]: con.hgetall("pythonDict")
Out[102]:
{b'Address': b'Mumbai',
b'Company': b'SCTL',
b'Last Name': b'Rajpurohit',
b'Location': b'Ahmedabad',
b'Name': b'Mangu Singh'}
In [103]: con.hmset("pythonDict", {"Location": "Ahmedabad", "Company": ["A/C Pri
...: sm", "ECW", "Musikaar"]})
Out[103]: True
In [104]: con.hgetall("pythonDict")
Out[104]:
{b'Address': b'Mumbai',
b'Company': b"['A/C Prism', 'ECW', 'Musikaar']",
b'Last Name': b'Rajpurohit',
b'Location': b'Ahmedabad',
b'Name': b'Mangu Singh'}
In [105]: con.hget("pythonDict", "Name")
Out[105]: b'Mangu Singh'
In [106]: con.hmget("pythonDict", "Name", "Location")
Out[106]: [b'Mangu Singh', b'Ahmedabad']
I hope, it makes things more clear.
我希望,它能使事情变得更加清晰。