Tutorial Study Image

Python pop()

Python 中的 pop() 函数有助于从字典中删除并返回指定的键元素。此方法的返回值应该是被删除项的值。


dictionary.pop(key[, default]) #where key which is to be searched
 

pop() 参数

pop() 函数接受两个参数。Python 还支持列表 pop,它从列表中删除指定索引的元素。如果未提供索引,则将删除最后一个元素。

参数 描述 必需/可选
您要删除的项的键名 必需
默认值 如果指定的键不存在,则返回的值。 可选

pop() 返回值

pop() 的返回值取决于给定的参数。

输入 返回值
键存在 从字典中删除/弹出的元素
键不存在 默认值
键不存在且未提供默认值 KeyError 异常

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:如何弹出字典中不存在但提供了默认值的元素


# 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