當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Python Dictionary popitem()用法及代碼示例

Python popitem() 方法從字典中刪除一個元素。它刪除任意元素並返回其值。如果字典為空,則返回錯誤 KeyError。該方法的語法如下。

簽名

popitem()

參數

沒有參數

返回

它返回彈出的元素。

讓我們看一些 popitem() 方法的例子來了解它的函數。

Python字典popitem()方法示例1

讓我們先看一個使用 popitem() 方法刪除元素的簡單示例。

# Python dictionary popitem() Method
# Creating a dictionary
inventory = {'shirts':25, 'paints':220, 'shocks':525, 'tshirts':217}
# Displaying result
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}

Python字典popitem()方法示例2

如果字典為空,則返回錯誤 KeyError。請參閱下麵的示例。

# Python dictionary popitem() Method
# Creating a dictionary
inventory = {}
# Displaying result
print(inventory)
p = inventory.popitem()
print("Removed",p)
print(inventory)

輸出:

KeyError:'popitem():dictionary is empty'

Python字典popitem()方法示例3

在此示例中,我們將刪除和更新字典以了解此方法的函數。

# Python dictionary popitem() Method
# Creating a dictionary
inventory = {'shirts':25, 'paints':220, 'shocks':525, 'tshirts':217}
# Displaying result
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}






相關用法


注:本文由純淨天空篩選整理自 Python Dictionary popitem() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。