Python 3 7 字典 dict 學習

2021-10-05 20:05:00 字數 1981 閱讀 1903

python中,字典(dict) 是一種內建的對映型別,也是惟一的;字典由鍵及其相應的值組成,這種鍵-值對稱為項(item)。

定義

dict1 =

# 空字典

# python 是完全動態資料型別,同乙個字典value型別可以是多種的

dict2 =

print

(dict2)

#

獲取項數(鍵-值對數)
length =

len(dict2)

print

(length)

# 3

刪除項
del dict2[

'website'

]# 通過key刪除項

# dict2.clear() # 刪除掉所有項

print

(dict2)

#

新增項
dict2[

'website']=

''print

(dict2)

#

修改值
dict2[

'website']=

''# 通過key修改值

print

(dict2)

#

獲取值
website = dict2[

'website'

]# 通過 key 獲取值

print

(website)

#

獲取所有 key
keys = dict2.keys(

)print

(keys)

# dict_keys(['name', 'age', 'website'])

# 排序後獲取到的是list

keys =

sorted

(dict2.keys())

print

(keys)

# ['age', 'name', 'website']

獲取所有 value
values = dict2.values(

)print

(values)

# dict_values(['python3.7', 19, ''])

判斷 key 在字典中是否存在
if

'mykey'

in dict2:

print

('字典中存在 `mykey`')if

'mykey'

notin dict2:

print

('字典中不存在 `mykey`'

)

遍歷字典
# 遍歷 key

for key in dict2:

value = dict2[key]

print

(key, value)

# 遍歷 value

for value in dict2.values():

print

(value)

# 遍歷 key,value

for key, value in dict2.items():

print

(key, value)

將字串格式設定功能用於字典
# format_map 會自動查詢與引數名一樣的key,並獲取值

desc =

'python home is '

.format_map(dict2)

print

(desc)

# python home is

desc =

' home is '

.format_map(dict2)

print

(desc)

# python3.7 home is

Python3 字典dict 排序

首先說明一點 python的dict這個東西是沒辦法按照指定順序的key存的 一 按key排序 1,直接從dict輸出,只要保證輸出結果的順序是按key排序就可以了 2,按key儲存為其他一種資料格式 比如list,或者 collections.ordereddict 之後,進行輸出。這樣輸出的結果...

Python學習筆記6 字典Dict

python內建了字典 dict的支援,dict全稱dictionary,在其他語言中也稱為map,使用鍵 值 key value 儲存,具有極快的查詢速度。person person name keven type person dict 字典可以原地修改,即它是可變的。dict1 id dict...

Python學習9 字典dict的使用

filename dict.py 字典初始化方式 dict1 dict2 dict name python version 3.4 使用fromkeys方法時,第二個引數如果為空,則所有的鍵值為none.dict3 fromkeys name version dict4 fromkeys name ...