Python四大金剛之字典詳解
發(fā)布日期:2021-12-22 18:06 | 文章來源:源碼之家
引言

列表、字典:可變序列,可以執(zhí)行增刪改排序等
字典:無序的


一、字典的創(chuàng)建
#使用{}創(chuàng)建
scores = {'張三':100 ,'李四':98 ,'王麻子':72}
print(scores)
print(type(scores))
#使用內(nèi)置函數(shù)dict()
student = dict(name = 'jack ', age = 16)
print(student)
print(type(student))
二、字典元素的操作
(一)獲取

#獲取字典中的元素
#方法一:
print(scores['張三'])
#方法二:
print(scores.get('張三'))
print(scores.get('66'))
#如果查找的不存在,返回none
(二)增刪改

刪除操作
del scores['張三'] #根據(jù)索引刪除 key 和value print(scores) scores.clear() #刪除所有 print(scores)
新增操作 (直接增加)
scores['趙四'] = 80
三、獲取字典的視圖

# 獲取所有key值 key = scores.keys() print(key) print(type(key)) print(list(key)) #將key組成的視圖轉(zhuǎn)成list #獲取所有value值 value = scores.values() print(value) print(type(value)) print(list(value)) #將value組成的視圖轉(zhuǎn)成list #獲取所有的key-value值 items = scores.items() print(items) print(type(items)) print(list(items)) #轉(zhuǎn)換為list后元素由元組組成

四、字典的遍歷

for item in scores : print(item,end=' ') #輸出的是字典中的key #輸出key對應(yīng)的value print(scores[item],end=' ') print(scores.get(item))
五、字典的特點

六、字典生成式


students = ['mark','sheep','jerry','tom']
grades = [100,78,60,59]
d={key:price for key,price in zip(students,grades)}
print(d)
總結(jié)
本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關(guān)注本站的更多內(nèi)容!
引言

列表、字典:可變序列,可以執(zhí)行增刪改排序等
字典:無序的


一、字典的創(chuàng)建
#使用{}創(chuàng)建
scores = {'張三':100 ,'李四':98 ,'王麻子':72}
print(scores)
print(type(scores))
#使用內(nèi)置函數(shù)dict()
student = dict(name = 'jack ', age = 16)
print(student)
print(type(student))
二、字典元素的操作
(一)獲取

#獲取字典中的元素
#方法一:
print(scores['張三'])
#方法二:
print(scores.get('張三'))
print(scores.get('66'))
#如果查找的不存在,返回none
(二)增刪改

刪除操作
del scores['張三'] #根據(jù)索引刪除 key 和value print(scores) scores.clear() #刪除所有 print(scores)
新增操作 (直接增加)
scores['趙四'] = 80
三、獲取字典的視圖

# 獲取所有key值 key = scores.keys() print(key) print(type(key)) print(list(key)) #將key組成的視圖轉(zhuǎn)成list #獲取所有value值 value = scores.values() print(value) print(type(value)) print(list(value)) #將value組成的視圖轉(zhuǎn)成list #獲取所有的key-value值 items = scores.items() print(items) print(type(items)) print(list(items)) #轉(zhuǎn)換為list后元素由元組組成

四、字典的遍歷

for item in scores : print(item,end=' ') #輸出的是字典中的key #輸出key對應(yīng)的value print(scores[item],end=' ') print(scores.get(item))
五、字典的特點

六、字典生成式


students = ['mark','sheep','jerry','tom']
grades = [100,78,60,59]
d={key:price for key,price in zip(students,grades)}
print(d)
總結(jié)
本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關(guān)注本站的更多內(nèi)容!
版權(quán)聲明:本站文章來源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非maisonbaluchon.cn所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場,如有內(nèi)容涉嫌侵權(quán),請聯(lián)系alex-e#qq.com處理。
相關(guān)文章
關(guān)注官方微信