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