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


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

Python pop() 方法從字典中刪除一個元素。它刪除與指定鍵關聯的元素。

如果字典中存在指定的鍵,則刪除並返回其值。

如果指定的鍵不存在,則會拋出錯誤 KeyError。

簽名

pop(key[, default])

參數

key:刪除與其關聯的值的鍵。

defaults:如果鍵不存在,則返回默認值。

返回

它刪除並返回與指定鍵關聯的值。

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

Python字典pop()方法示例1

從字典中彈出元素的簡單示例。它返回彈出的值。請參閱下麵的示例。

# Python dictionary pop() Method
# Creating a dictionary
inventory = {'shirts':25, 'paints':220, 'shock':525, 'tshirts':217}
# Calling method
element = inventory.pop('shirts')
# Displaying result
print(element)

輸出:

25

Python字典pop()方法示例2

如果 key 不存在,則返回錯誤 KeyError。請參閱下麵的示例。

# Python dictionary pop() Method
# Creating a dictionary
inventory = {'shirts':25, 'paints':220, 'shock':525, 'tshirts':217}
# Calling method
element = inventory.pop('shoes')
# Displaying result
print(element)

輸出:

KeyError:'shoes'

Python字典pop()方法示例3

如果 key 不存在,我們可以設置默認值以避免錯誤 KeyError。請參閱示例。

# Python dictionary pop() Method
# Creating a dictionary
inventory = {'shirts':25, 'paints':220, 'shock':525, 'tshirts':217}
# Calling method
element = inventory.pop('shoes',100)
# Displaying result
print(element)

輸出:

100

Python字典pop()方法示例4

再看一個例子來了解 pop() 方法的函數。

# Python dictionary pop() Method
# Creating a dictionary
inventory = {'shirts':25, 'paints':220, 'shocks':525, 'tshirts':217}
# Displaying result
print(inventory)
# Pop using default value
p = inventory.pop('shirts')
print("Removed",p,"shirts")
print(inventory)

輸出:

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






相關用法


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