“Python/gloss python remove dictionary items”的版本间差异
来自菜鸟教程
小 (Pywikibot 4.4.0.dev0) |
小 (机器人:添加分类Python基础教程) |
||
第140行: | 第140行: | ||
</div> | </div> | ||
<br /> | <br /> | ||
+ | |||
+ | [[分类:Python基础教程]] |
2020年10月29日 (四) 08:48的最新版本
<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)