9. Python pop()

发布时间:2023-12-08

Python pop()

更新:2022-07-24 12:58 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 }