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)
亲自试一试 »

