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