Python - 刪除字典項
刪除項
有幾種方法可以從字典中刪除項
示例
pop()
方法刪除具有指定鍵名的項
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.pop("model")
print(thisdict)
自己動手試一試 »
示例
popitem()
方法刪除最後插入的項(在 3.7 版本之前,會隨機刪除一個項)
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.popitem()
print(thisdict)
自己動手試一試 »
示例
del
關鍵字刪除具有指定鍵名的項
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict["model"]
print(thisdict)
自己動手試一試 »
示例
del
關鍵字也可以完全刪除字典
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict
print(thisdict) # 這將導致錯誤,因為 "thisdict" 不再存在。
自己動手試一試 »
示例
clear()
方法清空字典
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.clear()
print(thisdict)
自己動手試一試 »