字典無序的,可變的數據類型python
用於存儲大量數據,字典要比列表快,將數據和數據之間進行關聯面試
lst1 = ['常鑫','李文虎','張宇'] # 姓名 lst2 = [10,80,100] # 分數 print(lst1[0],lst[0])
逗號分隔叫作一個元素app
{鍵 : 值,鍵 : 值} ——鍵值對code
字典以散列表和哈希表存儲索引
字典的鍵必須是可哈希的——不可變的數據類型——避免哈希衝突使用了(開放尋址法)get
不可哈希的——可變的數據類型:列表it
要求惟一——若是有重複的後面的將前面的覆蓋for循環
字典的值:能夠任意class
定義:dic = {} dic = {"常鑫":10,"李文虎":80,"張宇":100,10:"大黑哥",True:123,(1,2,3):"大煎餅",[1,2]:"meet"} print(dic)
dic = {'常鑫':[1,2,3],'李文虎':'89'} dic['李文虎'] = 99 print(dic)
用李文虎這個鍵去字典進行查詢,若是不存在就執行添加,若是存在就不添加變量
dic = {'常鑫':[1,2,3],'李文虎':'89'} dic.setdefault('李文虎':'99') print(dic) print(dic.setdefault('李文虎'))
dic = {'常鑫':[1,2,3],'李文虎':'89'} del dic['常鑫'] print(dic)
也有返回值:返回的是被刪除的值
dic = {'常鑫':[1,2,3],'李文虎':'89'} print(dic.pop('常鑫')) print(dic)
dic = {'常鑫':[1,2,3],'李文虎':'89'} dic.clear() print(dic)
dic = {'常鑫':[1,2,3],'李文虎':'89'} dic['常鑫'] = 'dsb' print(dic)
dic = {"常鑫":[1,2,3],'李文虎': '89'} dic1 = {"1":3,"5":9,"李文虎":100} dic1.update(dic) print(dic1)
dic = {"常鑫":[1,2,3],'李文虎': '89'} for i in dic: print(i)
dic = {"常鑫":[1,2,3],'李文虎': '89'} print(dic.get('常鑫'))# 結果是[1,2,3] dic = {"常鑫":[1,2,3],'李文虎': '89'} print(dic.get('cx'))# 結果是None
dic = {"常鑫":[1,2,3],'李文虎': '89'} print(dic['常鑫']) # 結果是[1,2,3] dic = {"常鑫":[1,2,3],'李文虎': '89'} print(dic['cx']) # 報錯
dic = {"1":3,"5":9,"李文虎":100} for i in dic: print(i,dic.get(i)) # 獲取全部鍵和值
print(list(dic.keys())) # 獲取到列表
dic1 = {"1":3,"5":9,"李文虎":100} print(dic.keys()) # 結果是:高仿列表—— dic_keys(['1','5','李文虎']) # 獲取字典中全部的鍵 for i in dic.keys(): print(i) # 獲取字典中全部的值 lst = [] for i in dic: lst.append(dic[i]) print(lst)
print(list(dic.values())) # 獲取到列表
dic1 = {"1":3,"5":9,"李文虎":100} # 獲取字典中全部的值 print(list(dic.values())) # 結果是[3, 9, 100]
print(list(dic.items())) # 獲取到列表
dic1 = {"1":3,"5":9,"李文虎":100} print(dic.items()) # 結果是dict_items([('1', 3), ('5', 9), ('李文虎', 100)]) # 獲取字典的鍵和值 for i in dic.items(): print(i[0],i[1]) dic1 = {"1":3,"5":9,"李文虎":100} for i in dic1.items(): print(i) # 結果是 ('1', 3) ('5', 9) ('李文虎', 100) for k,v in dic1.items(): print(k,v) # 獲取每一個元素的鍵和值 # 結果是: 1 3 5 9 李文虎 100
a, b = 10,12 print(a) print(b) # 結果是 # 10 # 12 # 面試題 a = 10 b = 20 a,b = b,a print(a,b) # 結果:20 10 a,b = [1,2] print(a,b) # 結果是 1 2 a,b = (3,4) print(a,b) # 結果是: 1 2 a,b = "23" print(a,b) # 結果是: 2 3 工做以後可能會碰見 a,_,b = (3,4,5) print(a,b) # 等號後邊的值和前面的變量名要一一對應 a = 10,12 # 本質就是一個元組 print(a) # 結果是 (10,12) a,b = {"1":"a","2":"b"} # 獲得的是鍵 print(a,b) # 結果是 1 2
經過鍵一層一層的查找
# 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])