標籤:資料 rom update pytho date 基本 UI get 類型
1.字典的基本特徵:
key-value結構
key唯一,必須為不可變資料類型
value可以不唯一
無序
尋找速度快
2.建立一個字典:
info={“gaohui”:"IT",21,"PYTHON","hong":"stu",22,"java",2:3}
3.在字典裡增加內容:
info["aaa"]=任意形式的數
4.在字典裡刪除內容:
方法1:info.pop("gaohui")#刪除gaohui這個key
方法2:info.popitem()#隨機刪除
方法3:del info["gaohui"]#刪除gaohui這個key
5.在字典裡修改內容:
info["aaa"]=任意形式的數 這個aaa是字典裡的有的key值
6.查看字典裡的內容
"gaohui" in info #查看字典裡是否有gaohui這個key
info.get("gaohui") 擷取gaohui這個key中的內容
info["gaohui"]
兩種方法的區別:
#當使用info.get(),擷取的key為空白,此時輸出的值為none
#當使用info[]時,擷取的值為空白,此時會報錯
info.keys()#輸出字典的keys
info.values()#輸出字典keys中的內容
7.info.update
info={"gaohui":[21,"man","IT"],"hongyan":[23,"woman","student"],"aaa":[22,"bbb","ccc"]}
info2={"aa":2,2:3,"hongyan":[22,"woman","student"]}
info.update(info2)#當info2和info中的key相同時,info2中的內容會把info中的內容覆蓋,此時列印出來的key重複的地方就是info2中的值
8.info.setdefault
info2={"aa":2,2:3,"hongyan":[22,"woman","student"]}
info2.setdefault(2,"aaa")#如果你的字典中有2這個key,那麼輸出為字典中key2對應的值,如果沒有2這個key,那麼輸出為aaa
9.info.fromkeys
info2={"aa":2,2:3,"hongyan":[22,"woman","student"]}
# print(info2.fromkeys(["a","b","c"],"gaohui"))#批量製造一個value都相同的字典
10.字典迴圈
for k in info2:
print(k,info2[k])#字典迴圈,列印出key及對應的value
python入門之字典