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) #this will cause an error because "thisdict"
no longer exists.
ตัวอย่าง
วิธี การclear()
ล้างพจนานุกรม:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.clear()
print(thisdict)