【Python】Python - 刪除Dictionary items。Python Remove Dictionary Items.
【Python】Python - 刪除Dictionary items。Python Remove Dictionary Items.
有許多的 methods可以刪除dictionary的items。
範例
The pop() 方法使用key name去移除item。
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.pop("model")
print(thisdict)上面輸出: {'brand': 'Ford', 'year': 1964}範例
The popitem() 方法移除最後新增入的item。但在python 3.6或更早的版本則會移除隨機的item,因為這些版本的python dictionary沒有排序。
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.popitem()
print(thisdict)上面輸出: {'brand': 'Ford', 'model': 'Mustang'}範例
The del keyword會刪除特定key值的item。
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict["model"]
print(thisdict)上面輸出: {'brand': 'Ford', 'year': 1964}範例
The del keyword 會將整個dictionary完整的刪除:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict
print(thisdict) #this will cause an error because "thisdict" no longer exists.上面輸出: Traceback (most recent call last): File "./test.py", line 7, in <module>NameError: name 'thisdict' is not defined範例
The clear() 方法會清空dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.clear()
print(thisdict)上面輸出: {}
留言
張貼留言