有多种方法可以从字典中删除项目:
这个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)
亲自试一试 »
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!