1. 程式人生 > 實用技巧 >Python redis hash雜湊用法

Python redis hash雜湊用法

■ Python操作redis的hash結構方法定義:

常用的操作方法:

1,hset(name, key, value) ---- 更新一條資料的屬性,沒有則新建

2,hget(name, key) ---- 讀取這條資料的指定屬性, 返回字串型別

3,hmset(name, mapping) ---- 批量更新資料(沒有則新建)屬性

4,hmget(name, keys, *args) ----批量讀取資料(沒有則新建)屬性

5,hgetall(name) ---- 獲取這條資料的所有屬性和對應的值,返回字典型別

6,hkeys(name) ---- 獲取這條資料的所有屬性名,返回列表型別

6,hdel(name, *keys) ---- 刪除這條資料的指定屬性

import redis
 
r = redis.Redis(host="127.0.0.1", port=6379, db=0)
# 新建一條鍵名為"123456"的資料, 包含屬性attr_1
r.hset("123456", "attr_1", 100)
# 更改鍵名為"123456"的資料, 更改屬性attr_1的值
r.hset("123456", "attr_1", 200)
 
# 取出屬性attr_1的值
attr_1 = r.hget("123456", "attr_1")
 
# 輸出看一下(發現屬性值已經為str)
print "-- get attr_1:", attr_1
 
# 屬性集合
attr_dict = {
    "name": "常成功",
    "alias": "常城",
    "sex": "male",
    "height": 175,
    "postal code": 100086,
    "Tel": None,
}
# 批量新增屬性
r.hmset("123456", attr_dict)
 
# 取出所有資料(返回值為字典)
h_data = r.hgetall("123456")
 
# 輸出看一下(取出來的時候都變成了str)
print "-- get all attr:", h_data
 
# 刪除屬性(可以批量刪除)
r.hdel("123456", "Tel")
 
# 取出所有屬性名
h_keys = r.hkeys("123456")