字典類型

一、映射:通過任意鍵查找集合中值信息的過程,python中通過字典實現映射。字典是鍵值對的集合。

passwd={"China":"BigCountry","Korean":"SmallCountry","France":"MediumCountry"}

print passwd

運行結果:
{"China":"BigCountry","Korean":"SmallCountry","France":"MediumCountry"}
二、字典的基本操作:
(1)爲字典增加一項
dictionaryName[key]=value
(2)刪除字典中的一項
del dictionaryName[key]
(3)字典的遍歷

for key in students:
    print(key+":"+str(students[key]))

(4)遍歷字典的鍵key

for key in dictionaryName.keys():
    print(key)

(5)遍歷字典的值value

for value in dictionaryName.values():
    print(value)

(6)遍歷字典的項

passwd={"China":"BigCountry","Korean":"SmallCountry","France":"MediumCountry"}
for item in passwd.items():
    print(item)

運行結果:

('China', 'BigCountry')
('Korean', 'SmallCountry')
('France', 'MediumCountry')

(7)遍歷字典的key-value

passwd={"China":"BigCountry","Korean":"SmallCountry","France":"MediumCountry"}
for item,value in passwd.items():
    print(item,value)

運行結果:

China BigCountry
Korean SmallCountry
France MediumCountry

(8)判斷一個鍵是否在字典中in或not in

>>>passwd={"China":"BigCountry","Korean":"SmallCountry","France":"MediumCountry"}

>>>"China" in passwd
True
>>>"America" in passwd
False

(9)clear()刪除字典中的所有項目
get(key)返回字典中key對應的值
pop(key)刪除並返回字典中key對應的值
update(字典)將字典中的鍵值添加到字典中

>>>passwd={"China":"BigCountry","Korean":"SmallCountry","France":"MediumCountry"}
>>>passwd.get("China")
"BigCountry"
>>>passwd.pop(Korean)
"SmallCountry"
>>>passwd
{"China":"BigCountry","France":"MediumCountry"}
>>>passwd.clear()
>>>passwd
{}
發佈了32 篇原創文章 · 獲贊 30 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章