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