Python四大金剛之字典詳解
更新時間:2021年10月20日 11:09:28 作者:4343
這篇文章主要介紹了Python的字典,小編覺得這篇文章寫的還不錯,需要的朋友可以參考下,希望能夠給你帶來幫助
引言
列表、字典:可變序列,可以執(zhí)行增刪改排序等
字典:無序的
一、字典的創(chuàng)建
#使用{}創(chuàng)建 scores = {'張三':100 ,'李四':98 ,'王麻子':72} print(scores) print(type(scores)) #使用內置函數dict() student = dict(name = 'jack ', age = 16) print(student) print(type(student))
二、字典元素的操作
(一)獲取
#獲取字典中的元素 #方法一: print(scores['張三']) #方法二: print(scores.get('張三')) print(scores.get('66')) #如果查找的不存在,返回none
(二)增刪改
刪除操作
del scores['張三'] #根據索引刪除 key 和value print(scores) scores.clear() #刪除所有 print(scores)
新增操作 (直接增加)
scores['趙四'] = 80
三、獲取字典的視圖
# 獲取所有key值 key = scores.keys() print(key) print(type(key)) print(list(key)) #將key組成的視圖轉成list #獲取所有value值 value = scores.values() print(value) print(type(value)) print(list(value)) #將value組成的視圖轉成list #獲取所有的key-value值 items = scores.items() print(items) print(type(items)) print(list(items)) #轉換為list后元素由元組組成
四、字典的遍歷
for item in scores : print(item,end=' ') #輸出的是字典中的key #輸出key對應的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)
總結
本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關注腳本之家的更多內容!
引言
列表、字典:可變序列,可以執(zhí)行增刪改排序等
字典:無序的
一、字典的創(chuàng)建
#使用{}創(chuàng)建 scores = {'張三':100 ,'李四':98 ,'王麻子':72} print(scores) print(type(scores)) #使用內置函數dict() student = dict(name = 'jack ', age = 16) print(student) print(type(student))
二、字典元素的操作
(一)獲取
#獲取字典中的元素 #方法一: print(scores['張三']) #方法二: print(scores.get('張三')) print(scores.get('66')) #如果查找的不存在,返回none
(二)增刪改
刪除操作
del scores['張三'] #根據索引刪除 key 和value print(scores) scores.clear() #刪除所有 print(scores)
新增操作 (直接增加)
scores['趙四'] = 80
三、獲取字典的視圖
# 獲取所有key值 key = scores.keys() print(key) print(type(key)) print(list(key)) #將key組成的視圖轉成list #獲取所有value值 value = scores.values() print(value) print(type(value)) print(list(value)) #將value組成的視圖轉成list #獲取所有的key-value值 items = scores.items() print(items) print(type(items)) print(list(items)) #轉換為list后元素由元組組成
四、字典的遍歷
for item in scores : print(item,end=' ') #輸出的是字典中的key #輸出key對應的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)
總結
本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關注腳本之家的更多內容!
相關文章
Python3.6+selenium2.53.6自動化測試_讀取excel文件的方法
這篇文章主要介紹了Python3.6+selenium2.53.6自動化測試_讀取excel文件的方法,本文通過實例代碼給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2019-09-09windows 10 設定計劃任務自動執(zhí)行 python 腳本的方法
這篇文章主要介紹了windows 10 設定計劃任務自動執(zhí)行 python 腳本的方法,本文圖文并茂給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2019-09-09