用鍵安全查找
如同影片示範,若你嘗試存取字典中不存在的鍵,會得到 KeyError。其中一種處理方式是使用 try: except: 區塊。你可以在《Python Data Science Toolbox (Part 1)》課程中進一步了解錯誤處理(https://www.datacamp.com/courses/python-data-science-toolbox-part-1)。
Python 也提供一個更快速且更通用的工具:.get() 方法。.get() 方法讓你提供鍵名,並在找不到該鍵時,選擇性地回傳你指定的值。
你將使用相同的 squirrels_by_park 字典。它的鍵是公園名稱,值是一個包含主要毛色、亮點、行為,以及對人類反應的元組。藉此你會練習使用 .get() 方法。
本練習屬於課程
Python 的資料型別
練習說明
- 從
squirrels_by_park字典中安全地印出'Union Square Park'。 - 從
squirrels_by_park字典中安全地印出'Fort Tryon Park'的型別。 - 從
squirrels_by_park字典中安全地印出'Central Park',或在找不到時印出'Not Found'。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Safely print 'Union Square Park' from the squirrels_by_park dictionary
print(____.____(____))
# Safely print the type of 'Fort Tryon Park' from the squirrels_by_park dictionary
print(____(squirrels_by_park.____('Fort Tryon Park')))
# Safely print 'Central Park' from the squirrels_by_park dictionary or 'Not Found'
print(____.get(____, ____))