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)
自己動手試一試 »