我们可以将Redis中的Hashes类型看成具有String Key和String Value的键值对容器。类似python中的dict,javascript的jaon,java 的map,每一个Hash可以存储4294967295个键值对。

 1 # encoding:utf-8
 2 import redis
 3 import time
 4 
 5 
 6 def main():
 7     """
 8     redis-cli -h 127.0.0.1 -a test321
 9     """
10     redis_host = "127.0.0.1"
11     redis_password = "test321"
12     redis_cli = redis.StrictRedis(host=redis_host, password=redis_password)
13     try:
14         key = "TEST_KEY_1484"
15         # string
16         print redis_cli.delete(key)
17         print redis_cli.hset(key, "test1", 1)  # 设置 key={test1:1}
18         print redis_cli.hget(key, "test1")  # 获取key[test1]
19         print redis_cli.hexists(key, "test1")  # 是否存在key[test1]
20         print redis_cli.hset(key, "test2", 2)  # 设置 key={test2:2}
21         print redis_cli.hlen(key)  # 查看key下的键值对数量
22         print redis_cli.hdel(key, "test1", "test2")  # 批量删除key下的键,返回实际删除的键数量
23         print redis_cli.hlen(key)  # 查看key下的键值对数量
24         print redis_cli.hexists(key, "test1")  # 是否存在key[test1]
25         print redis_cli.hsetnx(key, "test1", 1)   # 设置 key={test1:1}
26         print redis_cli.hsetnx(key, "test1", 1.11)   # 如果key[test1]已存在设置失败
27         print redis_cli.hget(key, "test1")  # 获取key[test1]
28         print redis_cli.hincrby(key, "test1", 2)   # 设置 key[test1] 累加2
29         print redis_cli.hget(key, "test1")  # 获取key[test1]
30         print redis_cli.hset(key, "test2", 2)  # 设置 key={test2:2}
31         print redis_cli.hgetall(key)  # 获取key,得到dict对象
32         print redis_cli.hkeys(key)  # 获取key下的所有键,得到list对象
33         print redis_cli.hvals(key)  # 获取key下的所有值,得到list对象
34         print redis_cli.hmget(key, "test1", "test2")  # 批量获取key下的指定键,得到list对象
35         print redis_cli.hmset(key, {"test3": 3, "test4": 4})  # 批量设置键值,无则添加,有则覆盖,
36         print redis_cli.hgetall(key)
37     except Exception as e:
38         print e.message
39     finally:
40         print redis_cli.delete(key)
41     return None
42 
43 
44 if __name__ == "__main__":
45     main()

 github:https://github.com/luohuaizhi/test/blob/master/testRedisDict.py