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}

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

技术教程推荐

网络编程实战 -〔盛延敏〕

分布式技术原理与算法解析 -〔聂鹏程〕

OAuth 2.0实战课 -〔王新栋〕

Selenium自动化测试实战 -〔郭宏志〕

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

编程高手必学的内存知识 -〔海纳〕

搞定音频技术 -〔冯建元 〕

去无方向的信 -〔小麥〕

eBPF核心技术与实战 -〔倪朋飞〕

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