python入門之字典

來源:互聯網
上載者:User

標籤:資料   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入門之字典

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.