Python 从字典中删除项目
从字典中删除项目
有几种方法可以从字典中删除项目:
例子 1
pop() 方法删除拥有指定键名的项目:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.pop("model")
print(thisdict)
例子 2
popitem() 方法删除最后插入的项目(在 3.7 之前的版本中,会删除一个随机项目):
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.popitem()
print(thisdict)
例子 3
del 关键字删除拥有指定键名的项目:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict["model"]
print(thisdict)
例子 4
del 关键字也可以完全删除整个字典:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict
print(thisdict) # 这将导致错误,因为 "thisdict" 已不再存在。
例子 5
clear() 方法可清空字典:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.clear()
print(thisdict)