python 中的pop()
函數有助于從字典中移除并返回指定的鍵元素。此方法的返回值應該是被移除項的值。
**dictionary.pop(key[, default])** #where key which is to be searched
pop()
參數:
pop()
函數接受兩個參數。Python 還支持列表彈出,從列表中移除指定的索引元素。如果沒有提供索引,最后一個元素將被刪除。
參數 | 描述 | 必需/可選 |
---|---|---|
鍵 | 要刪除的項目的鍵名 | 需要 |
系統默認值 | 如果指定的鍵不存在,將返回的值。 | 可選擇的 |
pop()
返回值
pop()
的返回值取決于給定的參數。
| 投入 | 返回值 | | 密鑰存在 | 從字典中移除/彈出元素 | | 密鑰不存在 | 缺省值 | | 密鑰不存在&未給出默認值 | KeyError exception(密鑰錯誤異常) |
Python 中pop()
方法的示例
示例 1:如何用 python 從字典中彈出一個檸檬
# random fruits dictionary
fruits = { 'mango': 5, 'banana': 4, 'strawberry': 3 }
key = fruits.pop('mango')
print('The popped item is:', key)
print('The dictionary is:', fruits)
輸出:
The popped item is: 5
The dictionary is: {'banana': 4, 'strawberry': 3}
示例 2:如何彈出字典中沒有的元素
# random fruits dictionary
fruits = { 'mango': 5, 'banana': 4, 'strawberry': 3 }
key= fruits.pop('orange')
輸出:
KeyError: 'orange'
示例 3:如何彈出一個沒有出現在帶有 defalt 值的字典中的元素
# random fruits dictionary
fruits = { 'mango': 5, 'banana': 4, 'strawberry': 3 }
key = fruits.pop('orange', 'grapes')
print('The popped item is:', key)
print('The dictionary is:', fruits)
輸出:
The popped item is: grapes
The dictionary is: { 'banana': 4,'mango': 5,'strawberry': 3