開始使用免費開始

在字典中檢查資料

你可以使用 in 運算式來檢查某個鍵是否存在於字典中。

例如,你可以用 if 'cookies' in recipes: 來檢查 'cookies' 是否是 recipes 字典中的鍵。這能讓你在字典裡有資料時安全地做出對應處理。

我們已載入一個 squirrels_by_park 字典,鍵是公園名稱,值是由松鼠資料所組成的字典清單。

本練習屬於課程

Python 的資料型別

檢視課程

練習說明

  • 檢查 Tompkins Square Park 是否在 squirrels_by_park 字典中;如果存在,印出 'Found Tompkins Square Park'
  • 檢查 Central Park 是否在 squirrels_by_park 中;如果找到就印出 'Found Central Park',否則印出 'Central Park missing'

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# Check to see if Tompkins Square Park is in squirrels_by_park
if "____" ____ ____:
    # Print 'Found Tompkins Square Park'
    print('Found Tompkins Square Park')
    
# Check to see if Central Park is in squirrels_by_park
if "____" ____ ____:
    # Print 'Found Central Park' if found
    print('Found Central Park')
else:
    # Print 'Central Park missing' if not found
    print('Central Park missing')
編輯並執行程式碼