無序,可修改,用於存儲數據,大量,比列表快,將數據和數據之間關聯python
定義:dict1 = {'cx':10,'liwenhu':80,'zhangyu':50}code
逗號分割的是一個元素,'cx'(鍵):10(值) -- 鍵值對blog
字典的鍵:要使用不可變數據類型(可哈希)。要求鍵惟一,若是有重複的,後面的會將前面的覆蓋。索引
可哈希的 -- 不可變的數據類型 - 避免哈希衝突使用了開放尋址法get
不可哈希的 -- 可變的數據類型it
字典的值能夠任意。io
dict1 = {'cx':10,'liwenhu':80,'zhangyu':50} #1 dict1['li'] = 89 print(dict1) #2 print(dict1.setdefault('liw')) dict1.setdefault('liw',100) print(dict1.setdefault('liw',100)) print(dict1)
del dict1['cx'] :經過查找字典的鍵刪除鍵值對,若是沒有會報錯。for循環
dict1.pop('cx'):經過字典的鍵刪除鍵值對,返回被刪除值class
dict1.clear():清空變量
dict1 = {'cx':10,'liwenhu':80,'zhangyu':50,'wu':20} #1 del dict1['cx'] print(dict1) #2 dict1.pop('wu') print(dict1.pop('wu')) print(dict1) #3 dict1.clear() print(dict1)
dict1['cx'] = 'dsb' 經過鍵,若是原字典中沒有此鍵對應的鍵值對,就是添加,若是有,就是修改
dict1.update(dict2) :update括號中的字典級別高於前邊的字典(括號中放的是要跟新的字典)
dict1 = {'cx':10,'liwenhu':80,'zhangyu':50} #2 dict2.update(dict1) print(dict2)
for 循環,獲取的是鍵。
dict1.get('cx') :經過鍵獲取值,若是沒有會返回None
dict1['cx'] :經過鍵獲取值,若是沒有會報錯。
dict1 = {'cx':10,'liwenhu':80,'zhangyu':50} #1 for i in dict1: print(i) #2 print(dict1.get('cx')) #3 print(dict1['cx'])
dic = {1001:["周杰倫","林俊杰"], 1002:{"汪峯":{"前妻1":["大燒餅"],"前妻2":["熊大","熊二"],"國際章":"肉絲"}}, 1003:{"陳冠希":["阿嬌","阿薩","張柏芝"]}, 1004:{"韋小寶":[{"教主夫人":["教主"]}, {"阿珂":"刺客"}, {"雙兒":"天地會"}, {"愛心覺羅建寧":"公主"}, {"獨臂神尼":{"韋小寶師父":{"蘭陵王":"隱身"},"花木蘭":[ "唧唧復唧唧","木蘭是戰士",{"爸爸":["花和尚"]}] }}, {"陳圓圓":"丈母孃"},{"穆建平":"小郡主"}]}, 1005:{"常鑫":["大黑哥","大燒餅","吃大煎餅","肉夾饃","自行車","井蓋",]} } # print(dic) # print(dic[1004]["韋小寶"][0]["教主夫人"][0]) # print(dic[1005]["常鑫"][-1]) # print(dic[1002]["汪峯"]["前妻2"][-1]) # print(dic[1004]["韋小寶"][4]["獨臂神尼"]["韋小寶師父"]["蘭陵王"]) # print(dic[1004]["韋小寶"][4]["獨臂神尼"]["花木蘭"][2]["爸爸"][0])
解構示意圖:
a = 10
b = 12
a,b = b,a
dict1 = {'cx':10,'liwenhu':80,'zhangyu':50} #1.鍵值對輸出 for i in dict1: print(i,dict1.get(i)) print(dict1.keys())#2.高仿列表 ,支持for循環,不支持索引-- 結果:ict_keys([True, 'zhangyu', 'cx', 'liwenhu']) for i in dict1.keys(): print(i) #print(dict1.keys()[0]) #3.dict1.values(),獲取全部的值(能夠轉列表) print(dict1.values()) print(list(dict1.values())) #4.dict1.items():獲取鍵值對 for i in dict1.items(): print(i) ##解構 for i,j in dict1.items():#解構輸出鍵值對 print(i,j) #5.解構。 a,b = 10 ,12 print(a) print(b) a = 10 b = 12 a,b = b,a print(a) print(b) a,b = [1,2] print(a,b) a,_,b = (3.4.5)#'_'無用,只爲將不要的4賦值進去 print(a,b)#等號後邊的值與前邊的變量數要一致 a = 10,12 print(a)#a是一個元組 a,b ={'1':'a','2':b} print(a,b)#取到的是鍵