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()用法及代碼示例
- Python Dictionary pop()用法及代碼示例
- Python Dictionary fromkeys()用法及代碼示例
- Python Dictionary clear()用法及代碼示例
- Python Dictionary update()用法及代碼示例
- Python Dictionary setdefault()用法及代碼示例
- Python Dictionary has_key()用法及代碼示例
- Python Dictionary get()用法及代碼示例
- Python Dictionary items()用法及代碼示例
- Python Dictionary copy()用法及代碼示例
- Python Dictionary keys()用法及代碼示例
- Python Dictionary values()用法及代碼示例
- Python Decimal shift()用法及代碼示例
- Python Decimal next_plus()用法及代碼示例
- Python Decimal logical_and()用法及代碼示例
- Python Decimal rotate()用法及代碼示例
- Python Decimal max_mag()用法及代碼示例
- Python Datetime.replace()用法及代碼示例
- Python Decimal as_integer_ratio()用法及代碼示例
- Python DataFrame.to_excel()用法及代碼示例
注:本文由純淨天空篩選整理自 Python Dictionary popitem() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。