Python 字典(二)

用書 PYTHON王者歸來 作者洪錦魁

遍歷字典

ClassA = {“Amy”:9,”Cindy”:20 ,”Landy”:30}

for name,number in ClassA.items():   

print(name)   

print(number)

print(“**************************************************”) 

for name in ClassA.keys():   

print(name) 

執行結果

遍歷VALUE

ClassA = {“Amy”:9,”Cindy”:20 ,”Landy”:30}  

for name in ClassA.keys():   

print(name)

for num in ClassA.values():   

print(num)

執行結果

排序 sorted

ClassA = {“Queen”:100,”Amy”:9,”Cindy”:20 ,”Landy”:30}  

for name in sorted(ClassA.keys()):   

print(name)

執行結果

ClassA = {“Queen”:100,”Amy”:9,”Cindy”:20 ,”Landy”:30}

print(ClassA)

ClassAlist = sorted(ClassA.items(),key =lambda item:item[1])

print(ClassAlist)

執行結果

建立字典串列

QOO = []for QOO_MEMBERS in range(50):   

QOOLIST ={“color”:”blue”,”score”:100,”speed”:”fast”}   

QOO.append(QOOLIST)

for QOOLIST in QOO[:5]:   

print(QOOLIST)

print(len(QOO))
for QOOLIST in QOO[41:45]:   

if QOOLIST[“color”]==”blue”:       

 QOOLIST[“color”]=”red”         

QOOLIST[“score”]=50         

QOOLIST[“speed”]=”fast”

for QOOLIST in QOO[40:46]:   

print(QOOLIST)

執行結果

字典的值是串列

NAMELIST = {“Susan”:[“Apple”,”Banana”],           

“Annie”:[“Peach”],           

“Susu”:[“Pizza”]}

for name ,fruits in NAMELIST.items():   

print(name)   

for friut in fruits:       

print(“”,friut)

執行結果

while 迴圈在字典的應用

namelist ={}

survey = True
while survey:   

name = input(“Please input your name:”)   

score = input(“Plese input your score:”)   

namelist[name] = score
repeat = input(“Do you want to submit survey?(y/n)”)   

if repeat != “y”:       

survey= False

for name ,score in namelist.items():   

print(name,”your score is:”,score)

執行結果

建立字典 fromkeys

seq=[“name”,”score”]

D1 =dict.fromkeys(seq)

print(D1)

D2 =dict.fromkeys(seq,”KYOTO”)

print(D2)seq=(“name”,”score”)

D3 =dict.fromkeys(seq)

print(D3)

D4= dict.fromkeys(seq,”HIROSHIMA”)

print(D4)

執行結果

傳回字典KEY的VALUE  .get   .setdefault

.get KEY若找不到就會傳DEFAULT值,若沒設DEFAULT值得話就傳回NONE

.setdefault 和 .get 基本上相同,但 .get 不會改變字典內容,但 .setdefault 若是鍵不在則會把鍵+DEFAULT加入預設值,沒有 DEFAULT 的話則是NONE

NAMELIST = {“Susan”:”Apple”,             “Annie”:”Peach”,             “Susu”:”Pizza” }
ret_value = NAMELIST.get(“Susan”)

print(ret_value)ret_value1 = NAMELIST.get(“Susu”)

print(ret_value1)ret_value2 = NAMELIST.get(“MOMO”)

print(ret_value2)ret_value3 = NAMELIST.setdefault(“Susan”)

print(ret_value3)ret_value4 = NAMELIST.setdefault(“KIKI”)

print(ret_value4)ret_value5 = NAMELIST.setdefault(“NINI”,”Milk”)

print(ret_value5)

執行結果

大型字典

class1 =[“Nini”,”Mimi”,”Kiki”,]

class2 =[“Momo”,”Koko”,”Roro”,]

class3 =[“Susu”,”Bubu”,”Nunu”,]

school ={“Class1″: class1,”Class2″:class2,”Class3”:class3}

type(school)

print(school)

執行結果