Python popitem()方法从字典中删除一个元素。它删除任意元素并返回其值。如果字典为空,则返回错误KeyError。该方法的语法如下。
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}
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)