Python3 中的 popItem()函数

首页 / Python3入门教程 / Python3 中的 popItem()函数

Python popitem()方法从字典中删除一个元素。它删除任意元素并返回其值。如果字典为空,则返回错误KeyError。该方法的语法如下。

popItem - 语法

popitem()

popItem - 返回

它返回弹出的元素。

无涯教程首先来看一个简单的示例,该示例使用popitem()方法删除元素。

无涯教程网

# Python dictionary popitem() Method
# Creating a dictionary
inventory = {'shirts': 25, 'paints': 220, 'shocks': 525, 'tshirts': 217}
# 显示结果
print(inventory)
p = inventory.popitem()
print("Removed",p)
print(inventory)

输出

{'shirts': 25, 'paints': 220, 'shocks': 525, 'tshirts': 217}
Removed ('tshirts', 217)
{'shirts': 25, 'paints': 220, 'shocks': 525}

如果字典为空,则返回错误KeyError。请参见下面的示例。

# Python dictionary popitem() Method
# Creating a dictionary
inventory = {}
# 显示结果
print(inventory)
p = inventory.popitem()
print("Removed",p)
print(inventory)

输出

KeyError: 'popitem(): dictionary is empty'

在此示例中,无涯教程将删除并更新字典以了解此方法的功能。

# Python dictionary popitem() Method
# Creating a dictionary
inventory = {'shirts': 25, 'paints': 220, 'shocks': 525, 'tshirts': 217}
# 显示结果
print(inventory)
p = inventory.popitem()
print("Removed",p)
print(inventory)
inventory.update({'pajama':117})
print(inventory)

输出

{'shirts': 25, 'paints': 220, 'shocks': 525, 'tshirts': 217}
Removed ('tshirts', 217)
{'shirts': 25, 'paints': 220, 'shocks': 525}
{'shirts': 25, 'paints': 220, 'shocks': 525, 'pajama': 117}

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

玩转Git三剑客 -〔苏玲〕

Go语言从入门到实战 -〔蔡超〕

透视HTTP协议 -〔罗剑锋(Chrono)〕

分布式系统案例课 -〔杨波〕

动态规划面试宝典 -〔卢誉声〕

小马哥讲Spring AOP编程思想 -〔小马哥〕

深入浅出分布式技术原理 -〔陈现麟〕

LangChain 实战课 -〔黄佳〕

工程师个人发展指南 -〔李云〕

好记忆不如烂笔头。留下您的足迹吧 :)