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)
自己动手试一试 »