iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 22
0
AI & Data

AI的本_資料科學打基礎系列 第 22

[Day 22]遍歷字典

  • 分享至 

  • twitterImage
  •  

在大型coding中,字典用久了會產生相當數量的元素,也許幾千筆或是幾十萬筆甚至更多
該怎麼遍歷字典的鍵,值,鍵:值對應

items() 遍歷字典的鍵:值

可以讓我們取得字典的鍵:值 配對的元素

for name,team in players.items():
    print('\n 姓名:',name)
    print('隊名: ',team)

https://ithelp.ithome.com.tw/upload/images/20190923/20119806TugzDOht3x.jpg
python的字典dict是一個無序的資料結構,只會保持鍵:值,不會關注元素的排列順序
items()只傳回一個元組,上面的範例,我們是利用name,team分別取得所傳回的元組內容
https://ithelp.ithome.com.tw/upload/images/20190923/20119806Q6tGR5jEex.jpg

遍歷字典的鍵 keys()

如果不想要取得字典的值(value),只想要鍵(keys),可以用keys()搭上for 迴圈來遍歷字典的鍵

for name in players.keys():
    print('\n 姓名:',name)

https://ithelp.ithome.com.tw/upload/images/20190923/20119806B6etA6VYjy.jpg

https://ithelp.ithome.com.tw/upload/images/20190923/2011980668gI31eQBP.jpg

https://ithelp.ithome.com.tw/upload/images/20190923/20119806y0Oy6wKKsN.jpg

遍歷字典的值 values()

https://ithelp.ithome.com.tw/upload/images/20190923/20119806BvZCs6NJFi.jpg

上面的例子中,Golden State Warriors有重複出現,但是在字典的應用中鍵不可有重複,但是值可以重複
如果希望所列的值不重要,可以使用集合set觀念使用Set()函數
https://ithelp.ithome.com.tw/upload/images/20190923/20119806XpyN0HeMKv.jpg


上一篇
[Day 21] 字典的後續
下一篇
[Day 23] 字典 串列 字典
系列文
AI的本_資料科學打基礎30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言