刪除 Python 中的字典元素
你可以刪除單獨的字典元素,也可以清空字典的全部內容。你還可以用一個操作刪除整個字典。
要明確刪除整個字典,只需使用 del 語句。
示例
下面是一個簡單的示例 −
#!/usr/bin/python
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
del dict['Name']; # remove entry with key 'Name'
dict.clear(); # remove all entries in dict
del dict ; # delete entire dictionary
print "dict['Age']: ", dict['Age']
print "dict['School']: ", dict['School']輸出
會生成以下結果,注意,會引發異常,因為在 del dict 之後,字典將不復存在 −
dict['Age']: Traceback (most recent call last): File "test.py", line 8, in <module> print "dict['Age']: ", dict['Age']; TypeError: 'type' object is unsubscriptable
注意 − del() 方法將在下一部分討論。
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP