2018-10-26
閱讀量:
765
Python字典類(lèi)型
字典類(lèi)型是Python中一種非序列的存儲(chǔ)結(jié)構(gòu),存儲(chǔ)的是鍵值對(duì)(key:value),其存儲(chǔ)形式為 d={key1:value1, key2:value2},其中<鍵>是唯一不重復(fù)的,<值>可以不唯一。
# ==== 構(gòu)建字典類(lèi)型數(shù)據(jù) ====
students={"203-2012-045":"John","203-2012-037":"Peter"} # 大括號(hào)創(chuàng)建字典
# 輸出結(jié)果
print(students)
{'203-2012-045': 'John', '203-2012-037': 'Peter'}
# ==== 向已有字典里增加數(shù)據(jù)項(xiàng) ====
students["202-2011-121"]="Susan" # 中括號(hào)添加字典
# 輸出結(jié)果
print(students)
{'203-2012-045': 'John', '203-2012-037': 'Peter', '202-2011-121': 'Susan'}
# ==== 查詢字典中的值 ====
students["203-2012-045"]
# 輸出結(jié)果
'John'
# ==== 刪除字典中的一項(xiàng) ====
del students["203-2012-037"]
# 輸出結(jié)果
print(students)
{'203-2012-045': 'John', '202-2011-121': 'Susan'}
# ==== 字典遍歷 ====
for key in students:
print(key) # 輸出key值
print(students[key]) # 輸出value值
print(key + ":" + str(students[key])) # 輸出key-value值
# 輸出結(jié)果
203-2012-045
John
203-2012-045:John
==============
202-2011-121
Susan
202-2011-121:Susan
# ==== 判斷鍵key是否在字典中 ====
"203-2012-045" in students # Output顯示True/False
# 輸出結(jié)果
True
# ==== 構(gòu)建字典類(lèi)型數(shù)據(jù) ====
students={"203-2012-045":"John","203-2012-037":"Peter"}
# ==== 顯示字典中所有的key ====
tuple(students.keys())
# 輸出結(jié)果
('203-2012-045', '203-2012-037')
# ==== 顯示字典中所有的value ====
tuple(students.values())
# 輸出結(jié)果
('John', 'Peter')
# ==== 顯示字典中所有的key-value ====
tuple(students.items())
# 輸出結(jié)果
(('203-2012-045', 'John'), ('203-2012-037', 'Peter'))
# ==== 獲取字典中key對(duì)應(yīng)的值 ====
students.get("203-2012-045")
# 輸出結(jié)果
'John'
# ==== 刪除字典中key對(duì)應(yīng)的值 ====
students.pop("203-2012-045")
students
# 輸出結(jié)果
'John'
{'203-2012-037': 'Peter'} #students中刪除了'John'
# ==== 刪除字典中所有的值 ====
students.clear()
students
# 輸出結(jié)果
{} #students被清空






評(píng)論(0)


暫無(wú)數(shù)據(jù)
CDA考試動(dòng)態(tài)
CDA報(bào)考指南
推薦帖子
0條評(píng)論
0條評(píng)論
0條評(píng)論