使用字典

Python 的資料型別

Jason Myers

Instructor

建立並迴圈走訪字典

  • 以鍵/值配對儲存資料
  • 可巢狀(在字典中以字典作為某鍵的值)
  • 可迭代
  • dict(){} 建立
art_galleries = {}

for name, zip_code in galleries:
    art_galleries[name] = zip_code
Python 的資料型別

在迴圈中列印

for name in sorted(art_galleries)[-5:]:
    print(name)
Zwirner David Gallery
Zwirner & Wirth
Zito Studio Gallery
Zetterquist Galleries
Zarre Andre Gallery
Python 的資料型別

安全地用鍵查找

art_galleries['Louvre']
|--------------------------------------------------------------------
KeyError                            Traceback (most recent call last)
<ipython-input-1-4f51c265f287> in <module>()
--> 1 art_galleries['Louvre']

KeyError: 'Louvre'
  • 以鍵當索引即可從字典取得值
  • 若索取不存在的鍵,會拋出 KeyError 並讓程式停止
Python 的資料型別

安全地用鍵查找(續)

  • .get() 方法可安全存取鍵,無需錯誤或例外處理
  • 若鍵不存在,.get() 預設回傳 None,也可提供要回傳的替代值
art_galleries.get('Louvre', 'Not Found')
'Not Found'
art_galleries.get('Zarre Andre Gallery')
'10011'
Python 的資料型別

一起來練習吧!

Python 的資料型別

Preparing Video For Download...