Python dict字典的使用

2021-10-10 04:54:04 字數 2677 閱讀 8337

為記錄學習的過程

python中 雜湊值 hash()

在字典dict中 每個鍵值對的key 儲存到 記憶體中都是以雜湊值 位址值key 的方式儲存的

每次獲取相同值的雜湊值都是相等的 這樣保證了一致性 ,假如重啟專案 則雜湊值會發生變化

如果是數字型別的雜湊值 hash(123455) 數字在python 中 其數字本身就是對應的雜湊值

print

(hash

("abc"))

print

(hash

("bcd"))

print

(hash

(1233211234))

print

(hash

("abc"))

dict1=

dict2=

for k,v in dict1.items():

if k ==

1233211234

:print

(hash

(k))

for k,v in dict2.items():

if k ==

1233211234

:print

(hash

(k))

# 字典的更新與刪除

dict2 =

print

(dict2)

print

("ages"

in dict2)

# 判斷是否包含 存在

print

("name1"

in dict2)

# 單個key 更新

dict2[

"name"]=

"李四"

print

(dict2)

# 多個key 一起更新

dict2.update(name=

"王五"

, age=18)

print

(dict2)

# 新增操作秉承 上面的操作一樣 有則更新 無則新增

dict2[

"address"]=

"重慶"

print

(dict2)

dict2.update(address=

"北京"

)print

(dict2)

# 刪除乙個key 並返回刪除的值

print

("***xx"*10

)delete = dict2.pop(

"address"

,"這是未刪除到返回的預設值"

)print

(dict2.pop(

"address22"

,"這是未刪除到返回的預設值"))

print

(delete)

print

(dict2)

# 預設刪除最後乙個key

delete2 = dict2.popitem(

)print

(delete2)

print

(dict2)

# 清除所有資料

dict2.clear(

)print

(dict2)

# 設定字典 dict json 預設值的方式

name1 =

name2 =

# 方式1

# if "grade" not in name2:

# name2["grade"]="c"

# 方式2 使用dict.setdefault() 方法 設定預設值 存在則不更新 不存在則新增

name2.setdefault(

"grade"

,"c"

)print

(name1)

print

(name2)

# 字典 dict json items 檢視的操作 需要記住 好東西!!!!!!!!!!!!!!!!!1

# dict.keys dict.values dict.items 為 鍵、值、鍵值對 檢視格式化 type() 後 他們的資料結構並不是普通的dict 結構, 該結構為 dict_***x

# 在對原dict 資料操作時 檢視化資料也會跟著變化 相當於原dict 的子集 並沒有完全分離開

# 也可以理解為mysql 中的 檢視 如果原資料發生了變化 則資料庫中檢視的資料也會跟著發生變化

keys = name1.keys(

)values = name1.values(

)items = name1.items(

)print()

print

(values)

print

(items)

# 測試開始對原資料進行操作

name1[

"address"]=

"重慶"

print

(keys)

print

(values)

print

(items)

# 把字典 dict json 資料格式化

# 新版本方式 str.format_map(dict) 的方式對字串進行格式化

str1 =

"我的名字是:,今年歲了,我來自"

.format_map(name1)

print

(str1)

python dict 字典 操作

名稱 唯一性資料型別 可變性key 鍵 唯一 數字 字串 元組 不可value 值 不唯一 任意可變 dict assert dict 通過指定key值訪問對應的value dict assert dict say hello assert dict 20 hi 60 不存在時 報keyerror ...

Python dict 字典 詳細總結

d d.has key name 如果有key返回true d.get name 如果沒有key返回none 賦值可以是字元,數字,列表,元組,字典。d age 28 d friends john megan alex del d name 刪除指定key d.clear 清空字典d name 如果...

Python dict 字典 詳細總結

d d.has key name 如果有key返回true d.get name 如果沒有key返回none 賦值可以是字元,數字,列表,元組,字典。d age 28 d friends john megan alex del d name 刪除指定key d.clear 清空字典d name 如果...