#字典是key-value的數據類型,字典是無序的,沒有下標(列表有下標),key必須是唯一的
info = { "stu001":"fengxiaoli", "stu002":"cx", "stu003":"wyc", "stu004":"ljh", } ###-----------------循環字典 for i in info: #推薦使用 print(i,info[i]) for k,v in info.items(): #不推薦,因爲它是先轉化爲列表在打印,數據量的時候數據會很慢 print(k,v) ###-----------------查詢 print("stu001" in info) #判斷key是否在字典中,同py2中 info.has_key("stu001") print(info.get("stu002")) #通過key獲取value,推薦使用 print(info["stu001"]) print(info) ###-----------------修改 info["stu003"] = "fzl" #有那個key就修改,沒有新增 info["stu005"] = "fzl" print(info) ###-----------------刪除 del info #刪除整個字典 del info["stu005"] info.pop("stu004") info.popitem() #隨機刪除一組 ###-----------------合併兩個字典 b = { "stu001":"fxl", 3:5, 4:8, } info.update(b) #合併字典info和字典b,有重複的就更新,不重複的就合併 print(info) ###-----------------把字典轉成列表 print(info.items()) ###-----------------初始化一個字典 c = dict.fromkeys([7,8,9],"test") print(c) #輸出{8: 'test', 9: 'test', 7: 'test'} c1 = dict.fromkeys([7,8,9],{1:"feng",2:"cx",3:"fxl"}) print(c1) #輸出{8: {1: 'feng', 2: 'cx', 3: 'fxl'}, 9: {1: 'feng', 2: 'cx', 3: 'fxl'}, 7: {1: 'feng', 2: 'cx', 3: 'fxl'}} c1[8][2]="xia" #類似淺copy,二級字典中數據指向同一內存地址,修改一個所有都改變 print(c1) #輸出{8: {1: 'feng', 2: 'xia', 3: 'fxl'}, 9: {1: 'feng', 2: 'xia', 3: 'fxl'}, 7: {1: 'feng', 2: 'xia', 3: 'fxl'}} ###-----------------多級字典 info2 = { "stu001":{"fxl":["性別:男","年齡:21"]}, "stu002":{"cx":["性別:女","年齡:25"]}, "stu003":{"fzl":["性別:男","年齡:35"]}, } info2["stu001"]["fxl"][1] = "年齡:23" #修改 info2.setdefault("stu004",{"ljh":["性別:女","年齡:40"]}) #增加,如果字典中有這個key就不改變原值,沒有就新建 print(info2)
三級菜單練習
# Author:fengxiaoli Data={ "重慶":{ "綦江":{ "永城":["永城中學","永城小學"], "隆盛":["隆盛中學","隆盛小學"], "三角":["三角中學","三角小學"], "丁山":["丁山中學","丁山小學"], }, "永川":{}, "江北":{}, "沙坪壩":{}, }, "北京":{}, "上海":{}, "天津":{} } while True: for i in Data: print(i) choice1=input("1>>>>>") if choice1 in Data: while True: for j in Data[choice1]: print(j) choice2 = input("2>>>>>") if choice2 in Data[choice1]: while True: for k in Data[choice1][choice2]: print(k) choice3= input("3>>>>>") if choice3 in Data[choice1][choice2]: while True: for t in Data[choice1][choice2][choice3]: print(t) choice4= input("最後一層,返回按b:") if choice4 == "b": break elif choice4=="q": exit() if choice3 == "b": break elif choice3 == "q": exit() if choice2 == "b": break elif choice2 == "q": exit()