從字典中彈出與刪除
你常常會想從字典中移除鍵和值。你可以使用 Python 的 del 指令來做到。要特別注意,如果你嘗試刪除的鍵不存在,del 會拋出 KeyError。你不能把它和 .get() 方法一起用來安全刪除項目;不過,可以配合 try: catch: 使用。
如果你想把被刪除的資料儲存到另一個變數以便後續處理,.pop() 字典方法正好可以做到這點。你可以像使用 .get() 一樣,為 .pop() 提供一個預設值,以便安全地處理缺少的鍵。由於 .pop() 比 del 更安全,實務上也常以 .pop() 取代 del。
本練習屬於課程
Python 的資料型別
練習說明
- 從
squirrels_by_park中移除"Madison Square Park",並將其儲存為squirrels_madison。 - 以空字典作為預設值,安全地從
squirrels_by_park中移除"City Hall Park",並將其儲存為squirrels_city_hall。為此,將空字典{}作為.pop()的第二個引數傳入。 - 從
squirrels_by_ark中刪除"Union Square Park"。 - 列印
squirrels_by_park。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Remove "Madison Square Park" from squirrels_by_park
squirrels_madison = ____
# Safely remove "City Hall Park" from squirrels_by_park with an empty dictionary as the default
squirrels_city_hall = ____.____(____, ____)
# Delete "Union Square Park" from squirrels_by_park
____ ____[____]
# Print squirrels_by_park
print(squirrels_by_park)