python基礎(chǔ)之字典
發(fā)布日期:2021-12-21 10:08 | 文章來源:源碼中國(guó)
字典
# 字典:也是python中重要的數(shù)據(jù)類型,字典是由鍵值對(duì)組成的集合 # 通常使用 鍵來訪問數(shù)據(jù),效率非常高,和list一樣支持對(duì)數(shù)據(jù)的添加、修改和刪除操作 # 特點(diǎn): # 1.不是序列類型,沒有下標(biāo)的概念,是無序的鍵值集合,是python中內(nèi)置的高級(jí)數(shù)據(jù)類型‘ # 2.使用{}來表示字典對(duì)象,每個(gè)鍵值對(duì)使用逗號(hào)來分割 # 3.其鍵必須是不可變的類型【元組、字符串】 值可以是任意類型 # 4.每個(gè)鍵必定是唯一的,如果存在重復(fù)的鍵,那么后者會(huì)覆蓋前者,產(chǎn)生覆蓋 # 如何創(chuàng)建字典 dicta={} #空字典 print(type(dicta))
# 如何創(chuàng)建字典 dicta={"pro":'藝術(shù)','school':'北影'} # 添加字典數(shù)據(jù) dicta['name']='周雨彤' #key:value 直接賦值操作 dicta['age']='25' dicta['pos']='演員' # 結(jié)束添加 print(dicta) print(len(dicta)) ##數(shù)據(jù)項(xiàng)長(zhǎng)度 print(type(dicta))
dicta={"pro":'藝術(shù)','school':'北影'} # 添加字典數(shù)據(jù) dicta['name']='周雨彤' #key:value 直接賦值操作 dicta['age']='25' dicta['pos']='演員' # 修改數(shù)據(jù) print(dicta) #輸出完整的字典 print(dicta['name']) #通過鍵獲取對(duì)應(yīng)的值 dicta['name']='白鹿' #修改鍵對(duì)應(yīng)的值 dicta['school']='上戲' print(dicta)
# 獲取所有的鍵 print(dicta.keys()) #獲取所有的值 print(dicta.values()) #獲取所有的鍵和值 print(dicta.items())
# 獲取所有的鍵 print(dicta.keys()) #獲取所有的值 print(dicta.values()) #獲取所有的鍵和值 # print(dicta.items()) for key,value in dicta.items(): # print(item) print('%s==%s'%(key,value))
dicta.update({'age':32}) ##修改數(shù)據(jù) dicta.update({'height':1.75}) ##添加數(shù)據(jù) print(dicta)
# 刪除操作 del dicta['name'] #刪除指定鍵 dicta.pop('age')#通過指定鍵來進(jìn)行刪除 print(dicta)
print(dicta) # 如何排序 print(sorted(dicta.items(),key=lambda d:d[0]))
# 如何排序 #按照key排序 print(sorted(dicta.items(),key=lambda d:d[0])) #按照value排序 print(sorted(dicta.items(),key=lambda d:d[1]))
總結(jié)
本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關(guān)注本站的更多內(nèi)容!
版權(quán)聲明:本站文章來源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請(qǐng)保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場(chǎng),如有內(nèi)容涉嫌侵權(quán),請(qǐng)聯(lián)系alex-e#qq.com處理。
相關(guān)文章