Python/gloss python remove dictionary items

来自菜鸟教程
跳转至:导航、​搜索

<languages />

Python从字典中删除项目

从字典中删除项目

有几种方法可以从字典中删除项目:

The pop() 方法删除具有指定键名的项目:

thisdict =  {

  "brand": "Ford",

  "model": "Mustang",

  "year": 1964

}
thisdict.pop("model")

  print(thisdict)

The popitem() 方法删除最后插入的项(在3.7之前的版本中,将删除随机项):

thisdict =  {

  "brand": "Ford",

  "model": "Mustang",

  "year": 1964

}
thisdict.popitem()

  print(thisdict)

The del 关键字删除具有指定键名的项目:

thisdict =  {

  "brand": "Ford",

  "model": "Mustang",

  "year": 1964

}
del thisdict["model"]
print(thisdict)

The del 关键字也可以完全删除字典:

thisdict =  {

  "brand": "Ford",

  "model": "Mustang",

  "year": 1964

}
del thisdict
print(thisdict) #this will cause an error because "thisdict" 
  no longer exists.

The clear() 关键字清空字典:

thisdict =  {

  "brand": "Ford",

  "model": "Mustang",

  "year": 1964

}
thisdict.clear()
print(thisdict)