Python語言為幾乎所有容器(無論是列表容器還是集合容器)指定了pop()。這篇特別的文章著重說明Python詞典提供的pop()方法。這種方法對於經常處理字典的程序員很有用。
用法:dict.pop(key, def)
參數:
key:必須返回並刪除其鍵值對的鍵。
def:如果指定的鍵不存在,則返回的默認值。
返回:
如果存在鍵,則與已刪除鍵/值對關聯的值。
如果不存在 key ,則指定為默認值。
KeyError,如果不存在 key 且未指定默認值。
代碼1:演示工作pop()
,當存在 key 時。
# Python 3 code to demonstrate
# working of pop()
# initializing dictionary
test_dict = { "Nikhil" :7, "Akshat" :1, "Akash" :2 }
# Printing initial dict
print ("The dictionary before deletion:" + str(test_dict))
# using pop to return and remove key-value pair.
pop_ele = test_dict.pop('Akash')
# Printing the value associated to popped key
print ("Value associated to poppped key is:" + str(pop_ele))
# Printing dictionary after deletion
print ("Dictionary after deletion is:" + str(test_dict))
輸出:
The dictionary before deletion:{'Nikhil':7, 'Akshat':1, 'Akash':2} Value associated to poppped key is:2 Dictionary after deletion is:{'Nikhil':7, 'Akshat':1}
的行為pop()
當字典中不存在該鍵時,函數會有所不同。在這種情況下,如果沒有提供默認值,它將返回提供的默認值或KeyError。
代碼2:演示pop()在沒有 key 的情況下的工作
# Python 3 code to demonstrate
# working of pop() without key
# initializing dictionary
test_dict = { "Nikhil" :7, "Akshat" :1, "Akash" :2 }
# Printing initial dict
print ("The dictionary before deletion:" + str(test_dict))
# using pop to return and remove key-value pair
# provided default
pop_ele = test_dict.pop('Manjeet', 4)
# Printing the value associated to popped key
# Prints 4
print ("Value associated to poppped key is:" + str(pop_ele))
# using pop to return and remove key-value pair
# not provided default
pop_ele = test_dict.pop('Manjeet')
# Printing the value associated to popped key
# KeyError
print ("Value associated to poppped key is:" + str(pop_ele))
輸出:
The dictionary before deletion:{'Nikhil':7, 'Akshat':1, 'Akash':2} Value associated to poppped key is:4 Traceback (most recent call last): File "main.py", line 20, in pop_ele = test_dict.pop('Manjeet') KeyError:'Manjeet'
相關用法
- Python dict fromkeys()用法及代碼示例
- Python dict update()用法及代碼示例
- Python dict setdefault()用法及代碼示例
- Python dict items()用法及代碼示例
- Python dict keys()用法及代碼示例
- Python dict popitem()用法及代碼示例
注:本文由純淨天空篩選整理自manjeet_04大神的英文原創作品 Python Dictionary | pop() method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。