Python 中的 pop() 函数有助于从字典中删除并返回指定的键元素。此方法的返回值应该是被删除项的值。
dictionary.pop(key[, default]) #where key which is to be searched
pop() 函数接受两个参数。Python 还支持列表 pop,它从列表中删除指定索引的元素。如果未提供索引,则将删除最后一个元素。
| 参数 | 描述 | 必需/可选 |
|---|---|---|
| 键 | 您要删除的项的键名 | 必需 |
| 默认值 | 如果指定的键不存在,则返回的值。 | 可选 |
pop() 的返回值取决于给定的参数。
| 输入 | 返回值 |
|---|---|
| 键存在 | 从字典中删除/弹出的元素 |
| 键不存在 | 默认值 |
| 键不存在且未提供默认值 | KeyError 异常 |
# 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}
# random fruits dictionary
fruits = { 'mango': 5, 'banana': 4, 'strawberry': 3 }
key= fruits.pop('orange')
输出
KeyError: 'orange'
# 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