#字典是key-value data type, the dictionary is unordered, there is no subscript (the list has subscript), key must be unique
info = { "stu001": "Fengxiaoli", "stu002": "CX", "stu003": "Wyc", "stu004": "Ljh",}###-----------------Cycle dictionary For i in info: #推荐使用 print (I,info[i]) for k,v in info.items (): #不推荐, Because it is first converted to a list in print, the data amount of time is very slow print (K,V) ### -----------------Query Print ("stu001" in info) #判断key是否在字典中, same as Py2 Info.has_key ("stu001") Print (Info.get ("stu002")) #通过key获取value, print (info["stu001") is recommended for print ( Info) ###-----------------Modify info["stu003"] = "Fzl" #有那个key就修改, no new info["stu005"] = "Fzl" Print (Info) # # #-----------------Delete del info #删除整个字典del info["stu005"]info.pop ("stu004") Info.popitem () #随机删除一组 # # #-----------------Merge two dictionaries b = { "stu001": "FXL", 3:5, 4:8,}info.update (b) #合并字典info和字典b, with duplicate updates, Do not repeat the merge print (info) # # #-----------------Turn the dictionary into List print (Info.items ()) # # #-----------------Initialize a dictionary 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 ', &NBsp;3: ' FXL '}}c1[8][2]= "xia" #类似浅copy, the data in the two-level dictionary points to the same memory address, modifying one all changes print (c1 ) #输出 {8: {1: ' Feng ', 2: ' xia ', 3: ' fxl '}, 9: {1: ' Feng ', 2: ' xia ', 3: ' fxl '}, 7: {1: ' Feng ', 2: ' xia ', 3: ' FXL '}} ###-----------------Multi-level dictionary info2 = { "stu001": {" FXL ": [" Gender: Male "," Age: + "]}, " stu002 ": {" CX ": [" Gender: Female "," Age: "]}, " Stu003 ": {" Fzl ": [" Gender: Male "," Age: "]},}info2[" stu001 "] [FXL"][1] = "Age: #修改info2. SetDefault ("stu004", {"Ljh": ["Gender: Female", "Age: +]}) #增加, if this key in the dictionary does not change the original value, no new print (Info2)
Python---Dictionary