如何刪除字典元素?【每日一個(gè)知識(shí)點(diǎn)第189期-Python】
能刪單一的元素也能清空字典,清空只需一項(xiàng)操作。
顯示刪除一個(gè)字典用del命令,如下實(shí)例:
#!/usr/bin/Python3 dict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'} del dict['Name'] # 刪除鍵 'Name' dict.clear() # 清空字典 del dict # 刪除字典 print ("dict['Age']: ", dict['Age']) print ("dict['School']: ", dict['School'])
但這會(huì)引發(fā)一個(gè)異常,因?yàn)橛脠?zhí)行 del 操作后字典不再存在:
Traceback (most recent call last): File "test.py", line 9, in <module> print ("dict['Age']: ", dict['Age']) TypeError: 'type' object is not subscriptable
注:del() 方法后面也會(huì)討論。
《Python入門每日一個(gè)知識(shí)點(diǎn)》欄目是馬哥教育Python年薪20萬(wàn)+的學(xué)員社群特別發(fā)起,分享Python工具、Python語(yǔ)法、Python項(xiàng)目等知識(shí)點(diǎn),幫助大家快速的了解Python學(xué)習(xí),快速步入Python高薪的快車道。
http://www.vfuj.cn/73198.html